检查两个defaultdict的值是否都匹配相同的键

时间:2019-04-05 21:07:32

标签: python python-3.x defaultdict

我有两个defaultdicts,本质上我想看看两个字典中的值是否都匹配相同的对应键。例如:{1,4} {1,4}。因此,它将寻找匹配的键1,然后检查其值是否匹配4

所以我有:

keyOne = [30, 30, 60, 70, 90]
valueOne = [3, 4, 6, 7, 0]

KeyTwo = [30, 30, 60, 70, 90]
valueTwo = [4, 5, 6, -10, 9]

我这样创建两个defaultdicts

one = defaultdict(list)
for k, v in zip(keyOne, valueOne):
   one[k].append(v)

two = defaultdict(list)
for k, v in zip(keyTwo, valueTwo):
   two[k].append(v)

然后我想在键匹配但值不匹配的地方添加条目-所以我写了这个,但是不起作用:

three = defaultdict(list)

for k,v in one.items():
  for key in k:
    if key in two.items():
      if (value != v):
        three[k].append(value)

我不确定我要去哪里哪里,如果有人可以帮助我修复它,那将意味着很多。我是编程新手,真的想学习

1 个答案:

答案 0 :(得分:0)

您遇到了错字并可以简化循环:

from collections import defaultdict

keyOne = [30, 30, 60, 70, 90]
valueOne = [3, 4, 6, 7, 0]

keyTwo = [30, 30, 60, 70, 90]   # typo KeyTwo
valueTwo = [4, 5, 6, -10, 9] 

one = defaultdict(list)
for k, v in zip(keyOne, valueOne):
   one[k].append(v)

two = defaultdict(list)
for k, v in zip(keyTwo, valueTwo):
   two[k].append(v)
three = defaultdict(list)

for k1,v1 in one.items():   # there is no need for a double loop if you just want
    v2 = two.get(k1)        # to check the keys that are duplicate - simply query
    if v2:                  # the dict 'two' for this key and see if it has value
        three[k1] = [value for value in v2 if value not in v1]

    # delete key again if empty list (or create a temp list and only add if non empty)
    if not three[k1]:
        del three[k1]

print(three)

输出:

# all values in `two` for "keys" in `one` that are not values of `one[key]`
defaultdict(<class 'list'>, {30: [5], 70: [-10], 90: [9]})

如果关键字不在字典中,则使用dict.get(key)返回None并消除if-在检索之前进行检查。尽管您之后仍然需要if-但我认为这段代码“更干净”。

请参见Why dict.get(key) instead of dict[key]?