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:
For Python 3 below eliminates overhead of list conversion:
first = next(iter(prices.values()))
The dict
type is an unordered mapping, so there is no such thing as a "first" element.
What you want is probably collections.OrderedDict
.
d.keys()[0] to get the individual key.
Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections
prices = collections.OrderedDict((
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
))
prices.keys()[0]
'banana'
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".
easiest way is:
first_key = my_dict.keys()[0]
but some times you should be more careful and assure that your entity is a valuable list so:
first_key = list(my_dict.keys())[0]
As many others have pointed out there is no first value in a dictionary. The sorting in them is arbitrary and you can't count on the sorting being the same every time you access the dictionary. However if you wanted to print the keys there a couple of ways to it:
for key, value in prices.items():
print(key)
This method uses tuple assignment to access the key and the value. This handy if you need to access both the key and the value for some reason.
for key in prices.keys():
print(key)
This will only gives access to the keys as the keys()
method implies.