How to get the first key of a dictionary?
To get the first key of a dictionary, Python offers a variety of options.
get first key of dictionary using list()
To receive a list of keys, convert the dictionary to a list. The list includes all keys and then select the key with index 0.
# get first key of a dictionary using list()
myDict = {'firstKey': 'firstValue', 'secondKey': 'secondValue', 'thirdKey': 'thirdValue'}
myList = list(myDict)
print(myList[0])
The first key is returned.
firstKey
Please note that the operation can be considered expensive because a new list is created.
get first key of dictionary using loops
To get the first key of a dictionary, use a loop.
# get first key of dictionary using loops
myDict = {'firstKey': 'firstValue', 'secondKey': 'secondValue', 'thirdKey': 'thirdValue'}
for key, value in myDict.items():
print(key)
break
The first key is returned and the loop is ended after the first iteration.
firstKey
get first key dictionary using next() and iter()
To get the first key of a dictionary using next() and iter() functions.
# get first key of dictionary using next() and iter()
myDict = {'firstKey': 'firstValue', 'secondKey': 'secondValue', 'thirdKey': 'thirdValue'}
print(next(iter(myDict)))
The next element of the iter is returned.
firstKey