繁体   English   中英

Python词典:将键与所有键的值进行比较

[英]Python Dictionary: Compare keys with Values of All Keys

我正在解决一个问题,该问题要求我比较包含单词作为键和单词列表作为值的字典中的元素。 请参见下面的示例。

test_dict={'cubed': ['zryba', 'aszcb', 'btadc', 'melon', 'ewdgf'],
    'melon': ['jbilk', 'kcjml', 'cubed', 'nfmpo', 'ognqp'],
    'poop': ['mllm', 'nmmn', 'onno', 'qppq', 'rqqr']}

我想返回一个新字典,其中包含与字典中其他键的值匹配的键。 我的以下代码是错误的,我认为是因为它仅独立考虑每个键值对,并且仅比较这些对中的项。 有没有一种方法可以遍历键以获得所需的结果? 我想要的结果如下所示。

def find_matches(dict1):
    match_dict={}
    for key, value in dict1.items():
        for word in value:
            if key == word:
                #rotate_dict[key]=word
                match_dict[key].append(word)
    return match_dict

find_matches(SO_example) #returns {}, but should return {'cubed':'melon','melon':'cubed'}

谢谢您的帮助。

以下对我有用:

test_dict={'cubed': ['melon', '2', '3', '4', '5'],
           'melon': ['2', 'poop', '4', '5', '6'],
           'poop': ['3', '4', '5', '6', 'cubed']}

d = defaultdict(str)
# iterate over keys and values
for key, values in test_dict.items():
    # iterate over values
    for val in values:
        # if val is a key
        if val in [x for x in test_dict.keys() if x != key]:
            # set dict[key] = val
            d[key] = val
print(d) 

defaultdict(<class 'str'>, {'melon': 'poop', 'poop': 'cubed', 'cubed': 'melon'})

本质上,您将根据键列表检查所有值,当前键除外。 如果希望返回的字典包含多个值,请使用列表或集合:

defaultdict(list) or defaultdict(set)

并附加值

d[key].append(val) or d[key].add(val)

如果您的问题陈述正确,那么您的麻烦就在于您的test_dict是一个字典, test_dict字符串映射到列表列表,而不是将它们映射到单词列表。

您的find_matches函数遍历字典,将字符串key放入key而将list-of-words放入value

然后,您尝试迭代value 但是,如果将value设置为

[['gum', 'glove', 'knee']]

然后当你做

    for word in value:

可变word将取值为['gum', 'glove', 'knee'] ,然后循环将结束,因为value仅包含一个元素-三个单词的子列表。

您可以通过打印key然后在循环中打印每个word来确认这一点-我希望您只会看到一行带有单词列表的行。

要解决此问题,理想情况下,您将更改字典的格式。 为什么要存储1个单词列表? 为什么不直接存储单词列表呢?

如果由于某种原因无法做到这一点,那么您将需要决定如何进行:如果有多个单词列表,您是否要全部扫描它们,还是仅扫描第一个这样的列表?

# Scan the first list:
for word in value[0]:
    ...

# Scan all the lists:
for sublist in value:
    for word in sublist:
        ...

尝试:

test_dict = {'bat': [['gum', 'glove', 'knee']],
 'crowd': [['big', 'nice', 'large']],
 'glove': [['mitt', 'ball', 'bat']]}

def find_matches(dict1):
    match_dict = {}
    base_keys = dict1.keys()
    for key, values in dict1.items():
        for words in values:
            for base_key in base_keys:
                if base_key in words:
                    match_dict.update({key: base_key})
    return match_dict

print(find_matches(test_dict)) #{'bat': 'glove', 'glove': 'bat'}

for是因为你有一个[['mitt', 'ball', 'bat']]二维名单。

使用set可能更清楚

编辑

您在dict中发布没有示例值的另一个示例dict,sol很简单,删除一个for

test_dict={'cubed': ['zryba', 'aszcb', 'btadc', 'melon', 'ewdgf'],
    'melon': ['jbilk', 'kcjml', 'cubed', 'nfmpo', 'ognqp'],
    'poop': ['mllm', 'nmmn', 'onno', 'qppq', 'rqqr']}

def find_matches(dict1):
    match_dict = {}
    base_keys = dict1.keys()
    for key, values in dict1.items():
        for base_key in base_keys:
            if base_key in values:
                match_dict.update({key: base_key})
    return match_dict

print(find_matches(test_dict)) #{'cubed': 'melon', 'melon': 'cubed'}

您实际上可以通过dict理解来解决此问题。 您只需要遍历test_dict的名称和列表,直到找到同时存在于dict和列表中的名称:

>>> {n1:n2 for n1 in test_dict for n2 in test_dict[n1] if n2 in test_dict}
{'cubed': 'melon', 'melon': 'cubed'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM