How can I Python get first key in dict? I want to retrieve the first key from a dictionary. For example, given the dictionary:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
What is the simplest way to print “banana” from this dictionary?
Ah, the simplest way? Use next()
with iter()
to fetch the first key in a dictionary. This is both clean and efficient. Check it out:
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
first_key = next(iter(prices))
print(first_key) # Output: 'banana'
This works because iter(prices)
gives us an iterator over the dictionary keys, and next()
retrieves the first item.
Good one! Another easy method to achieve this is by converting the dictionary keys to a list using list()
. While slightly less efficient than Mark’s approach, it’s straightforward and readable:
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
first_key = list(prices.keys())[0]
print(first_key) # Output: 'banana'
This is helpful if you’re already working with lists or need to manipulate the keys further!
Nice! If you’re looking for a slightly old-school and intuitive way, a simple for
loop will do the trick. It’s a bit verbose but perfectly understandable for beginners:
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
for key in prices:
first_key = key
break
print(first_key) # Output: 'banana'
This approach is especially handy if you want to perform additional checks or operations as you iterate through the dictionary.