【问题标题】:Find values of keys in dictionary that contain a key word and return those keys and values在字典中查找包含关键字的键的值并返回这些键和值
【发布时间】:2016-11-14 00:55:21
【问题描述】:

我正在开发一个函数,我需要在包含关键字的字典中查找值并将它们(仅包含关键字的值)连同它们的键一起返回。我相信我的代码在正确的轨道上。

示例字典

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

所以如果我在搜索关键字“水彩”,函数应该返回这个

find_keyword(dictionary2(),'watercolor')

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

如您所见,该函数刚刚搜索了关键字水彩,并按照它们在字典中出现的顺序返回了键和值。我认为我当前的代码必须接近,但它目前给我一个断言错误并且每次都没有返回任何内容。有谁知道如何解决这个问题?

当前代码:

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

【问题讨论】:

  • "An" 错误信息永远不够,另请参阅How to Ask。
  • 您在find_keyword(..., keyword) 中使用keyword,然后在keyword = {} 中覆盖它
  • @furas 抱歉,我正在更改一些东西以使我的代码更清晰,希望我刚才的编辑可以修复它
  • 总是添加有问题的完整错误信息。
  • 使用print() 查看您在所有变量中的值。这可以帮助您解决问题。

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


【解决方案1】:
  • 使用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')}

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 2018-07-24
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2022-08-21
    相关资源
    最近更新 更多