warrior4223 warrior4223 - 23 days ago 6
Python Question

Returning specific key(s) and its value from a dictionary

I'm writing a function where I need to analyze a dictionary and pull out one of the keys and all of its values and return it.

Example dictionary:

{'P':[("Eight",1460, 225.0, 200.0, "fresco","Netherlands"),
("Six",1465,81.0, 127.1, "tempera", "Netherlands")],
'V':[("Four",1661, 148.0, 257.0,"oil paint", "Austria"),
("Two",1630, 91.0, 77.0, "oil paint","USA")],
'K':[("Five",1922,63.8,48.1,"watercolor","USA"),
("Seven",1950,61.0,61.0,"acrylic paint","USA"),
("Two",1965,81.3,100.3,"oil paint","United Kingdom")],
'C':[("Ten",1496,365.0,389.0,"tempera","Italy")],
'U':[("Nine",1203,182.0, 957.0,"egg tempera","Italy"),
("Twelve",1200,76.2,101.6,"egg tempera","France")]}


So if my function is called find_the_key and I was looking for 'C' and its value then it would need to return

find_the_key(dictionary2(),['C'])

return {'C': [('Ten', 1496, 365.0, 389.0, 'tempera','Italy')]}


If it needed to find both 'C' and 'V' it would return

find_the_key(dictionary2(),['C','V'])

return {'C': [('Ten', 1496, 365.0, 389.0, 'tempera', 'Italy')], 'V': [('Four',
1661, 148.0, 257.0, 'oil paint', 'Austria'), ('Two', 1630, 91.0, 77.0, 'oil
paint', 'USA')]}


I've done some research on extracting a key from a dictionary and my current code could be close.

def find_the_key(dictionary,thekey):
for thekey in dictionary.keys():
if dictionary[thekey] == targetkey:
return key, targetkey


Currently I'm getting the error targetkey is not defined though I think my logic is on the right track. Does anyone have any idea how to do this?

Answer

2 ways of doing it:

1) loop on input dictionary items scan the key in the key list each time, okay but doesn't use the fact that the input is a dictionary. If the key list or the input dictionary is very long it can take time (improve it slightly by turning key list into a set maybe)

def find_the_key(dictionary,thekey):
    return {k:v for k,v in dictionary.items() if k in thekey}

2) do the loop not in the dictionary, but in the asked keys, more logical and faster if the key list & the dictionary are big

def find_the_key(dictionary,thekey):
    return {k:dictionary[k] for k in thekey if k in dictionary}

Small drawback: test if k belongs and then get dictionary[k], which hashes k twice

3) classical, no listcomp, but only 1 access to the dictionary using get

def find_the_key(dictionary,thekey):
    d={}

    for k in thekey:
        v = dictionary.get(k)
        if k:
            d[k]=v
    return d

of course all methods yield the same results