简体   繁体   English

如何在Python中比较两个字典键?

[英]How to Compare Two Dictionary Keys in Python?

I want to compare two dictionary keys in python and if the keys are equal, then print their values. 我想比较python中的两个字典键,如果键相等,则打印它们的值。

For example, 例如,

dict_one={'12':'fariborz','13':'peter','14':'jadi'}
dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'}

and after comparing the keys, print 比较键之后,打印

'fariborz', 'daei'
'jadi', jafar'

You can iterate over the intersection of the keys of the two dicts, and print the corresponding values of the two dicts after mapping them to the repr function, which would help quote the strings: 您可以迭代两个字典的键的交集,并在将两个字典映射到repr函数后打印两个字典的对应值,这将有助于引用字符串:

for k in dict_one.keys() & dict_two.keys():
    print(','.join(map(repr, (dict_one[k], dict_two[k]))))

This outputs: 输出:

'fariborz','daei'
'jadi','jafar'

You're asking for the intersection of the two dictionaries. 您需要两个字典的交集。

Using the builtin type set 使用内置类型set

You can use the builtin type set for this, which implements the intersection() function. 您可以为此使用内置类型set ,该类型set可以实现intersection()函数。

You can turn a list into a set like this: 您可以将列表变成这样的集合:

set(my_list)

So, in order to find the intersection between the keys of two dictionaries, you can turn the keys into sets and find the intersection. 因此,为了找到两个字典的键之间的交点,可以将键变成集合并找到交点。

To get a list with the keys of a dictionary: 要获得带有字典键的列表:

dict_one.keys()

So, to find the intersection between the keys of two dicts: 因此,要找到两个字典的键之间的交集:

set(dict_one.keys()).intersection(set(dict_two.keys()))

This will return, in your example, the set {'12', '14'} . 在您的示例中,这将返回集合{'12', '14'}

The code above in a more readable way: 上面的代码更具可读性:

keys_one = set(dict_one.keys())
keys_two = set(dict_one.keys())
same_keys = keys_one.intersection(keys_two)
# To get a list of the keys:
result = list(same_keys)

Using anonymous function (lambda function) and list comprehension 使用匿名函数(lambda函数)和列表理解

Another easy way to solve this problem would be using lambda functions. 解决此问题的另一种简便方法是使用lambda函数。

I'm including this here just in case you'd like to know. 如果您想知道的话,我将其包括在这里。 Probably not the most efficient way to do! 可能不是最有效的方法!

same_keys = lambda first,second: [key1 for key1 in first.keys() if key1 in second.keys()]

So, as to get the result: 因此,为了得到结果:

result = same_keys(dict_one,dict_two)

Any of the above two methods will give you the keys that are common to both dictionaries. 以上两种方法中的任何一种都将为您提供两个词典共有的键。

Just loop over it and do as you please to print the values: 只需在其上循环并按照您的喜好打印值即可:

for key in result:
    print('{},{}'.format(dict_one[key], dict_two[key]))

You can use the & operator with to find the matching keys 您可以将&运算符与查找匹配的键

for i in d1.keys() & d2.keys():
    print("'{}', '{}'".format(d1[i], d2[i]))
 ~/python/stack/sept/twenty_2$ python3.7 alice.py 'fariborz', 'daei' 'jadi', 'jafar 
for key, val1 in dict_one.items():
    val2 = dict_two.get(key)
    if val2 is not None:
        print(val1, val2)

Take iteration through one dictionary and check for existence of key in the other: 通过一个字典进行迭代,并检查另一个字典中是否存在密钥:

dict_one = {'12':'fariborz','13':'peter','14':'jadi'}
dict_two = {'15':'ronaldo','16':'messi','12':'daei','14':'jafar'}

for k in dict_one:
    if k in dict_two:
        print(dict_one[k], dict_two[k])


# fariborz daei
# jadi jafar

Dictionaries are nice in python because they allow us to look up a key's value very easily and also check if a key exists in the dict. 字典在python中很好用,因为它们使我们可以非常轻松地查找键的值,还可以检查字典中是否存在键。

So in your example if you want to print the values for whenever the keys are the same between the dicts you can do something like this: 因此,在您的示例中,如果您希望在字典之间的键相同时打印值,则可以执行以下操作:

dict_one={'12':'fariborz','13':'peter','14':'jadi'}
dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'}

# Loop through all keys in dict_one
for key in dict_one:
    # Then check if each key exists in dict_two
    if key in dict_two:
        val1 = dict_one[key]
        val2 = dict_two[key]
        print('{},{}'.format(val1, val2))  # print out values with comma between them
def compare(dict1,dict2):
  keys1 = dict1.keys()
  keys2 = dict2.keys()
  for key in keys1:
    if key in keys:
      print(dict1[key],dict2[key])

Using intersection .then you can get the same key value from dict_one and dict_two 使用交集。然后您可以从dict_onedict_two获得相同的键值

This is my code: 这是我的代码:

dict_one={'12':'fariborz','13':'peter','14':'jadi'}
dict_two={'15':'ronaldo','16':'messi','12':'daei','14':'jafar'}
print([(dict_one[vals],dict_two[vals]) for vals in dict_one.keys() & dict_two.keys()])

Output 产量

 [('fariborz', 'daei'), ('jadi', 'jafar')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM