简体   繁体   English

如何从python中的哪个字典中查找哪个键

[英]How to find which key is from which dictionary in python

(In python) I have two dictionaries which are present in a list . (在python中)我有两个字典存在于list中。 Then i retrieved the non matching keys from the two dictionaries wrt comparing keys only. 然后我从两个字典中检索了不匹配的键,仅比较了键。

But now my requirement is how to know which key is from which dictionary 但是现在我的要求是如何知道哪个字典的钥匙

My Code 我的密码

first = dict(a=1, b=2) 
second = dict(b=0, c=3) 
for i in range(1): 
    diff = set(first) ^ set(second) 
print diff 

This shall help you. 这将为您提供帮助。 You can edit your code like this: 您可以像这样编辑代码:

first = dict(a=1, b=2) 
second = dict(b=0, c=3) 
for i in range(1): 
    diff = set(first) ^ set(second)
    key_of_first = set(first) - set(second)
    key_of_second = set(second) - set(first) 
print diff 
print key_of_first
print key_of_second

Let me know if it works for you or not. 让我知道它是否对您有用。

Output 输出量

set(['a', 'c'])
set(['a'])
set(['c'])

However, there is not need of for loop. 但是,不需要for循环。 It is there just because your code was having it initially. 在那里是因为您的代码最初具有它。

from __future__ import print_function

dict_one = {'a': 1, 'b': 2}
dict_two = {'b': 2, 'c': 3}

keys_only_in_dict_one = set(dict_one.keys()) - set(dict_two.keys())
print('Keys only in dict_one:', keys_only_in_dict_one)  # {'a'}

keys_only_in_dict_two = set(dict_two.keys()) - set(dict_one.keys())
print('Keys only in dict_two:', keys_only_in_dict_two)  # {c'}

all_non_matching_keys = keys_only_in_dict_one | keys_only_in_dict_two
print('All non-matching keys:', all_non_matching_keys)  # {'a', 'c'}

You could do this : 您可以这样做:

key="foo"

for i in arr: #arr is the list which contains the dictionaries
   if key in i.keys():
     print(i) # Or print something else

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

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