We can also fetch the key from a value by matching all the values using the dict. item() and then print the corresponding key to the given value.
Anything which can be stored in a Python variable can be stored in a dictionary value. That includes mutable types including list and even dict — meaning you can nest dictionaries inside on another. In contrast keys must be hashable and immutable — the object hash must not change once calculated.
Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.
You can assign a dictionary value to a variable in Python using the access operator [].
You should iterate over keys with:
for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
If you want to access both the key and value, use the following:
Python 2:
for key, value in my_dict.iteritems():
print(key, value)
Python 3:
for key, value in my_dict.items():
print(key, value)
The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this
Based on the above requirement this is what I would suggest:
keys = mydictionary.keys()
keys.sort()
for each in keys:
print "%s: %s" % (each, mydictionary.get(each))
If the dictionary contains one pair like this:
d = {'age':24}
then you can get as
field, value = d.items()[0]
For Python 3.5, do this:
key = list(d.keys())[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With