Python | Get the first key in dictionary
Many times, while working with Python, we can have a situation in which we require to get the initial key of dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kind. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + keys()
The combination of above methods can be used to perform this particular task. In this, we just convert the entire dictionaries’ keys extracted by keys() into a list and just access the first key.
# Python3 code to demonstrate working of # Getting first key in dictionary # Using keys() + list() # initializing dictionary test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Using keys() + list() # Getting first key in dictionary res = list(test_dict.keys())[0] # printing initial key print("The first key of dictionary is : " + str(res)) |
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The first key of dictionary is : best
Method #2 : Using next() + iter()
This task can also be performed using these functions. In this, we just take the first next key using next() and iter function is used to get the iterable conversion of dictionary items.
# Python3 code to demonstrate working of # Getting first key in dictionary # Using next() + iter() # initializing dictionary test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Using next() + iter() # Getting first key in dictionary res = next(iter(test_dict)) # printing initial key print("The first key of dictionary is : " + str(res)) |
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The first key of dictionary is : best
Recommended Posts:
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python | Convert string dictionary to dictionary
- Python | Pretty Print a dictionary with dictionary value
- Python Dictionary
- Python | Get key from value in Dictionary
- Add a key:value pair to dictionary in Python
- Python | Nested Dictionary
- Few mistakes when using Python dictionary
- Second largest value in a Python Dictionary
- Python dictionary | values()
- Python | Value summation of key in dictionary
- Python | Check if key has Non-None value in dictionary
- Python | Convert a set into dictionary
- Python | Dictionary with index as value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



