Python program to get first and last element in dictionary

WBOY
Release: 2023-09-07 17:01:02
forward
1209 people have browsed it

Python program to get first and last element in dictionary

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Developed by Gudio Van Rossum in 1991. It supports multiple programming paradigms, including structured, object-oriented, and functional programming. Before we dive into this topic, let's review the basic concepts relevant to the questions we provide.

A dictionary is a unique, mutable, and ordered set of items. Curly braces are used when writing dictionaries, and they contain keys and values: key names can be used to refer to dictionary objects. Data values ​​are stored in dictionaries in the form of key:value pairs.

The meaning of order and disorder

When we say that a dictionary is ordered, we mean that its contents have a certain order and will not change. Unordered items lack an explicit order, so the index cannot be used to find a specific item.

Example

See the following examples to better understand the concepts discussed above.

Please note that dictionary keys are case-sensitive; keys with the same name but different cases will be treated differently.

Dict_2 = {1: 'Ordered', 2: 'And', 3: 'Unordered'}
print (Dict_2)
Copy after login

Output

{1: 'Ordered', 2: 'And', 3: 'Unordered'}
Copy after login

Example

View the following examples to better understand the concept

Primary_Dict = {1: 'Grapes', 2: 'are', 3: 'sour'}
print("\nDictionary with the use of Integer Keys is as following: ")
print(Primary_Dict)

# Creating a Dictionary

# with Mixed keys
Primary_Dict = {'Fruit': 'Grape', 1: [10, 22, 13, 64]}
print("\nDicionary with the use of Mixed Keys is as following: ")
print(Primary_Dict)
Copy after login

Output

Dictionary with the use of Integer Keys is as following:
{1: 'Grapes', 2: 'are', 3: 'sour'}
Dictionary with the use of Mixed Keys:
{'Fruit': 'Grape', 1: [10, 22, 13, 64]}
Copy after login

When using Python, there are many situations where we need to obtain the primary key of the dictionary. It can be used for many different specific purposes, such as testing indexes or other similar purposes. Let's walk through some ways to get this done.

Use list() class keys()

A combination of the above techniques can be used to perform this specific task. Here we just create a list based on the keys collected from the complete dictionary with keys() and then access only the first entry. There is only one factor you need to consider before using it, its complexity. By iterating over each item in the dictionary, it first converts the entire dictionary to a list and then extracts its first member. The complexity of this method is O.(n).

Use the list() class to get the final key in the dictionary, such as last key = list(my dict)[-1]. The dictionary is converted into a list of keys via the list class, and the last key can be obtained by accessing the element at index -1.

Example

See the following examples for better understanding

primary_dict = {
   'Name': 'Akash',
   'Rollnum': '3',
   'Subj': 'Bio'
}
last_key = list(primary_dict) [-1]
print (" last_key:" + str(last_key))
print(primary_dict[last_key])
first_key = list(primary_dict)[0]
print ("first_key :" + str(first_key))
Copy after login

Output

last_key: Subj
Bio
first_key :Name
Copy after login

Example

The following program creates a dictionary named Primary_dict, which contains five key-value pairs. The entire dictionary is then printed to the screen, followed by the first and last keys of the dictionary.

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5}
print ("The primary dictionary is : " + str(primary_dict))
res1 = list (primary_dict.keys())[0]
res2 = list (primary_dict.keys())[4]
print ("The first key of the dictionary is : " + str(res1))
print ("the last key of the dictionary is :" + str(res2))
Copy after login

Output

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of the dictionary is : Grapes
the last key of the dictionary is : sweet
Copy after login

Example

If you only need the first key of the dictionary, an efficient way to obtain it is to use a combination of the "next()" and "iter()" functions. The iter() function is used to convert the dictionary entry into an iterable object, while next() gets the first key. The complexity of this approach is O(1). See the following examples for better understanding.

primary_dict = {'Grapes' : 1, 'are' : 2, 'sour' : 3, 'and' : 4, 'sweet' : 5}
print ("The primary dictionary is : " + str(primary_dict))
res1 = next(iter(primary_dict))
print ("The first key of dictionary is as following : " + str(res1))
Copy after login

Output

The primary dictionary is : {'Grapes': 1, 'are': 2, 'sour': 3, 'and': 4, 'sweet': 5}
The first key of dictionary is as following : Grapes
Copy after login

in conclusion

In this article, we explained two different examples of finding the first and last element from a dictionary. We also wrote a code to find only the first element of the dictionary by using next() iter().

The above is the detailed content of Python program to get first and last element in dictionary. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template