Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get dictionary key as variable directly in Python (not by searching from value)?

People also ask

Can I get a key from a dictionary from the value Python?

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.

Can dictionary keys be variables in Python?

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.

How do I extract a dictionary key in Python?

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.

Can a Python dictionary value be a variable?

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]