n00bprogrammer22 n00bprogrammer22 - 20 days ago 6
Python Question

Find values of keys in dictionary that contain a key word and return those keys and values

I'm working on a function where I need to find values in a dictionary that contain a keyword and return them (only the ones with the keyword) along with their keys. I believe my code is on the right track.

Example Dictionary

{'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
'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")],
'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 I was searching for the keyword 'watercolor' the function should return this

find_keyword(dictionary2(),'watercolor')

{'M': [('Three', 1430, 100.0, 102.0,
'watercolor', 'France')], 'K': [('Five',
1922, 63.8, 48.1, 'watercolor', 'USA')]}


As you can see the function just searched for the keyword watercolor and returned the keys and values in the order that they appeared in the dictionary. I think my current code must be close but it is currently giving me an Assertion error and returning nothing every time. Does anyone know how to fix this?

Current code:

def find_keyword(dictionary,theword):
keyword = {}
for key, record_list in dictionary.items():
for record in record_list:
value = record[1]
if theword in record:
if key in keyword:
keyword[key].append(record)
else:
keyword[key] = [record]
return keyword

Answer
  • Use an OrderedDict since you want to return the first match in your dict.
  • Your method has many unnecessary bells and whistles. Simply iterate thought your dict, search each key for your keyword, and return each key value pair that is a match.

from collections import OrderedDict
d = {'M':[("One",1400,30.0, 20.5,"oil paint","Austria"),("Three",1430,100.0,102.0,"watercolor","France")],
     '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")],
     '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")]}
d = OrderedDict(sorted(d.items(), key=lambda x:x[1], reverse=True))

# -------------- ########## ------------ #

def contains(seq, key):
     """
     Create A helper function to search for a key
     In a nested sequence of sequences.
     """
     return any(key in el for el in seq)

def find_key(d, key):
    """
    Iterate thought your `dict`, search each key for your keyword, and   
    return each key value pair that is a match.
    """
    tmp_dict ={}
    for k, v in d.items():
        for tup in v:
            if key in tup:
                tmp_dict[k] = tup
    return tmp_dict

print(find_key(d,'watercolor'))

Output:

{'M': ('Three', 1430, 100.0, 102.0, 'watercolor', 'France'),
 'K': ('Five', 1922, 63.8, 48.1, 'watercolor', 'USA')}
Comments