在字典中查找包含关键字的键值并返回这些键和值

时间:2016-11-14 00:55:22

标签: python python-3.x dictionary search words

我正在开发一个函数,我需要在字典中查找包含关键字的值,并返回它们(只有带关键字的值)及其键。我相信我的代码是在正确的轨道上。

示例词典

{'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")]
        }

因此,如果我在搜索关键字'watercolor',该函数应返回此

find_keyword(dictionary2(),'watercolor')

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

正如您所看到的那样,函数只搜索了关键字watercolor,并按字典中出现的顺序返回了键和值。我认为我当前的代码必须关闭,但它目前给我一个断言错误,并且每次都不返回任何内容。有谁知道如何解决这个问题?

当前代码:

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

1 个答案:

答案 0 :(得分:0)

  • 使用OrderedDict,因为您想要在dict中返回第一个匹配项。
  • 你的方法有许多不必要的花里胡哨。只需迭代您的dict,搜索关键字的每个键,然后返回匹配的每个键值对。
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'))

<强>输出:

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