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

2024-06-28 10:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个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)

我不知道我哪里出了问题,如果有人能帮我解决它,那将意味着很多。我是编程新手,非常想学习


Tags: keyinforitemsziponelistthree
1条回答
网友
1楼 · 发布于 2024-06-28 10:49:33

你有一个拼写错误,可以简化你的循环:

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]?

相关问题 更多 >