将一个字典键与另一个字典值进行比较并创建一个新字典

时间:2020-12-31 11:41:22

标签: python python-3.x dictionary

我想通过比较一个字典键和另一个字典值来创建一个新字典

我尝试了以下代码,但没有给出预期的结果

dictionary1 = {a: 1, b: 2}
dictionary2 = {2: d, 1: e}
common_pairs = dict()
for key in dictionary1:
    if (key in dictionary2 and dictionary1[key] == dictionary2[key]):
      common_pairs[key] = dictionary1[key]
print(common_pairs)

我期待如下输出

{a: e, b: d}

提前致谢!!

2 个答案:

答案 0 :(得分:3)

使用字典理解

# Valid dictionaries (i.e. key strings must be quoted, thus 'a' not a, etc.)
dictionary1 = {'a': 1, 'b': 2}
dictionary2 = {2: 'd', 1: 'e'}


# Dictionary comprehension (replace value in dictionary1 with lookup
# in dictionary2
result = {k:dictionary2[v] for k, v in dictionary1.items() if v in dictionary2}
print(result) # Output: {'a': 'e', 'b': 'd'}

# Alternative--place None when value not in dicstionary2
dictionary1 = {'a': 1, 'b': 2, 'c':3} # value 3 not in dictionary2
dictionary2 = {2: 'd', 1: 'e'}
result = {k:dictionary2.get(v, None) for k, v in dictionary1.items()}
# Output: {'a': 'e', 'b': 'd', 'c': None}

答案 1 :(得分:0)

没有字典理解:

List<? extends ZipEntry>