Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you print a key given a value in a dictionary for Python?

For example lets say we have the following dictionary:

dictionary = {'A':4,
              'B':6,
              'C':-2,
              'D':-8}

How can you print a certain key given its value?

print(dictionary.get('A')) #This will print 4

How can you do it backwards? i.e. instead of getting a value by referencing the key, getting a key by referencing the value.

like image 504
Jett Avatar asked Apr 03 '13 10:04

Jett


3 Answers

I don't believe there is a way to do it. It's not how a dictionary is intended to be used... Instead, you'll have to do something similar to this.

for key, value in dictionary.items():
    if 4 == value:
        print key
like image 119
SlxS Avatar answered Oct 17 '22 18:10

SlxS


In Python 3:

# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}

# To print a specific key (for instance the 2nd key which is at position 1)
print([key for key in x.keys()][1])

Output:

Y
like image 27
Fouad Boukredine Avatar answered Oct 17 '22 17:10

Fouad Boukredine


The dictionary is organized by: key -> value

If you try to go: value -> key

Then you have a few problems; duplicates, and also sometimes a dictionary holds large (or unhashable) objects which you would not want to have as a key.


However, if you still want to do this, you can do so easily by iterating over the dicts keys and values and matching them as follows:

def method(dict, value):
    for k, v in dict.iteritems():
        if v == value:
            yield k
# this is an iterator, example:
>>> d = {'a':1, 'b':2}
>>> for r in method(d, 2):
    print r

b

As noted in a comment, the whole thing can be written as a generator expression:

def method(dict, value):
    return (k for k,v in dict.iteritems() if v == value)

Python versions note: in Python 3+ you can use dict.items() instead of dict.iteritems()

like image 1
Inbar Rose Avatar answered Oct 17 '22 17:10

Inbar Rose