Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the first key in a dictionary?

I am trying to get my program to print out "banana" from the dictionary. What would be the simplest way to do this?

This is my dictionary:

prices = {     "banana" : 4,     "apple" : 2,     "orange" : 1.5,     "pear" : 3 } 
like image 931
slagoy Avatar asked May 21 '15 00:05

slagoy


People also ask

How do I find the first key-value pair in a dictionary?

In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. If you only care about getting the first value of a dictionary, you can use the dictionary values() function.

How do I search a dictionary key?

To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

What order are dictionary keys in?

As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default.


1 Answers

On a Python version where dicts actually are ordered, you can do

my_dict = {'foo': 'bar', 'spam': 'eggs'} next(iter(my_dict)) # outputs 'foo' 

For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.

For earlier Python versions, there is no "first key", but this will give you "a key", especially useful if there is only one.

like image 132
maxbellec Avatar answered Oct 03 '22 04:10

maxbellec