如何处理这两个词典以获取Python中的新词典?

时间:2014-02-28 18:04:26

标签: python python-2.7 dictionary

我有这两本词典;

Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)}
Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)}   

处理上述2个词典的输出字典是;

OutputDict = {1: ('John', 37), 2: ('Tom', 23)} 

获取OutputDict的逻辑是这样的;

(1)Dict1Dict2必须具有匹配的键。如果没有,OutputDict将丢弃来自Dict1的密钥:值对。 (2)如果找到匹配的密钥,则Dict1的值中的第2个元素必须与Dict2中的值不同。如果它们相同,则OutputDict会丢弃来自Dict1的密钥:值对。

如何在Python中编程?我使用的是Python 2.7。

3 个答案:

答案 0 :(得分:3)

您可以使用dictionary comprehension来遍历Dict1中的键值对,只保留这些键值对,以便(1)键位于Dict2; (2)数值与Dict1Dict2匹配:

<强>演示

>>> OutputDict = { k: v for k, v in Dict1.iteritems()
                   if k in Dict2 and int(Dict2[k][0]) != v[1] }
>>> OutputDict
{1: ('John', 37), 2: ('Tom', 23)}

答案 1 :(得分:2)

这是你想要的吗?

Dict1 = {1: ('John', 37), 2: ('Tom', 23), 3: ('Tom', 19), 4: ('Jane', 58)}
Dict2 = {1: ('2',), 2: ('4',), 3: ('19',)}
OutputDict = {k: v for (k, v) in Dict1.iteritems() if k in Dict2 and v[1] != int(Dict2[k][0])}
print OutputDict

输出:

{1: ('John', 37), 2: ('Tom', 23)}

答案 2 :(得分:2)

使用zip:

outDict = {i:Dict1[i] for i,j in zip(Dict1.keys(),Dict2.keys()) if i==j and int(Dict1[i][1]) != int(Dict2[i][0])}

输出:

 {1: ('John', 37), 2: ('Tom', 23)}