如何比较两个词典以检查两个词都是否存在

时间:2016-06-15 03:57:49

标签: python

我正在尝试比较两个字典,并使用以下逻辑检查dict1中的每个键是否存在(或不存在)dict2或dict3中的任何一个?有没有更好的方法来检查dict1中的任何键是否存在于dict2或dict3中并获得相应的值?

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};
dict3 = {'5678': '50.23'};

shared_keys1 = set(dict1).intersection(dict2)

shared_keys2 = set(dict1).intersection(dict3)

for key in shared_keys1:
    print( "Found Shared Key:{0}".format(key) )
    print( "dict1['{0}']={1}".format(key,dict2[key]) )


for key in shared_keys2:
    print( "Found Shared Key:{0}".format(key) )
    print( "dict1['{0}']={1}".format(key,dict3[key]) )

输出: -

Found Shared Key:1234
dict1['1234']=technici
Found Shared Key:5678
dict1['5678']=50.23

3 个答案:

答案 0 :(得分:3)

func buttonClicked(sender: UIButton){
    //your code here
}

是我怎么做的

shared_keys = set(dict1).intersection(dict2)

如果你想查看更多的dicts,你只需添加它们

>>> dict1 = {'1234': 'john','5678': 'james'}
>>> dict2 = {'1234': 'technician'};
>>> set(dict1).intersection(dict2)
set(['1234'])


>>> if set(dict1).intersection(dict2):
...     print "there is at least one key that is present in both dictionaries..."
...
there is at least one key that is present in both dictionaries...

答案 1 :(得分:3)

如果字典中存在密钥,body上的

in将会返回:

dict

所以你的代码可以写成:

>>> a = {'b': 1, 'c': '2'}
>>> 'b' in a
True
>>> 'd' in a
False

如果你只想检查两者是否相等,你可以这样做:

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};

for key in dict1.keys():
    print key
    if key in dict2:
        print dict1[key] + dict2[key]
    else:
        print dict1[key]

答案 2 :(得分:0)

for key in dict1:
    try:
        print dict1[key] + dict2[key]
    except KeyError:
        continue

您的第一个功能不需要将key或dict1作为参数。我不认为它做你想做的事情。那个for应该是if。它可以重写为:

def key_ispresent_in_dict2(key, dict2):
    if key in dict2.keys():
        return True
    return False

你走在正确的轨道上,可以将整个事情重写为:

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};

for key in dict1.keys():
    print key
    if key in dict2.keys():
        print dict1[key] + dict2[key]
    else:
        print dict1[key] 

并完全摆脱key_ispresent_in_dict2