Python Program to get first and last element from a 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 diving deep into the topic let’s first brush up the basic concepts related to the question provided to us.

A dictionary is a group of items that are unique, changing, and ordered. Curly brackets are used in dictionary writing, and they contain keys and values: The key name can be used to refer to dictionary objects. Data values are kept as key:value pairs in dictionaries.

Ordered and unordered meaning

When we refer to dictionaries as being ordered, we mean that the contents have a set order that won't change. Unordered items lack a clear order, making it impossible to use an index to find a specific item.

Example

See the following example to better understaning of the concept which is discussed above.

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

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

Output

{1: 'Ordered', 2: 'And', 3: 'Unordered'}

Example

See the following example for better understanding of 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)

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]}

Where using Python, there are numerous occasions when we would need to obtain the dictionary's primary key. It can be put to many different specific uses, such as testing the indexing or many more uses of this nature. Let's go over some methods for completing this work.

Using the list() class+ keys()

This specific task can be carried out using a combination of the aforementioned techniques. Here, we just create a list from the keys that keys() collected from the full dictionary and then only access the first entry. There is only one consideration you need make before employing this, namely its intricacy. By iterating over each item in the dictionary, it will first transform the entire dictionary to a list before extracting its first member. This approach's complexity would be O. (n).

Get the final key in a dictionary by using the list() class, as in last key = list(my dict)[-1]. The dictionary is transformed into a list of keys by the list class, and the last key may be obtained by accessing the element at index -1.

Example

See the following example 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))

Output

last_key: Subj
Bio
first_key :Name

Example

The following program creates a dictionary called Primary_dict with five key-value pairs. It then prints the entire dictionary to the screen, followed by printing out the first and last keys of the dictionary separately.

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))

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

Example

If you only need the first key of a dictionary, an efficient way to obtain it is by using the combination of the `next()` and `iter()` functions. The `iter()` function is used to convert dictionary entries into an iterable object, while `next()` grabs the first key. This approach has a complexity of O(1). See the following example 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))

Output

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

Conclusion

Here, in this article we have explained two different examples for finding out the first and last element from a dictionary. We have also written a code for finding out the first element only of a dictionary by using next()+ iter().

Updated on: 24-Apr-2023

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements