简体   繁体   English

比较两个字典列表,并在python中创建一个包含所有键和值的新列表

[英]Compare two list of dictionaries and create a new list with all keys and values in python

a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}]
b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}]

Here I have two list of dict. 在这里,我有两个字典列表。 I want to compare these and generate a new list like this: 我想比较这些并生成一个这样的新列表:

newlist = [{'a':{'a':1,'b':0}}, {'b':{'a':1,'b':1}}, {'c':{'a':0,'b':0}}]
A_list = [{'a':{'A':1}}, {'b':{}}]
B_list = [{'b': {'B': 1}}, {'a': {'A': 0}}]
list_with_all_keys = [{'a':{}}, {'b':{}}, {'c':{}}]
new_lod = [{k:{'A':(1 if k in A_list and 'A' in A_list[k] and A_list[k]['A'] is 1 else 0), 
               'B':(1 if k in B_list and 'B' in B_list[k] and B_list[k]['B'] is 1 else 0)}} 
           for k in [list(n.keys())[0] for n in list_with_all_keys]]

new_lod is then [{'a': {'B': 0, 'A': 0}}, {'b': {'B': 0, 'A': 0}}, {'c': {'B': 0, 'A': 0}}] new_lod然后是[{'a': {'B': 0, 'A': 0}}, {'b': {'B': 0, 'A': 0}}, {'c': {'B': 0, 'A': 0}}]

Note, that I added some upper-case letters, to clarify whats happening, it also work if you only use lower case letters a and b instead of A / A_list and B / B_list respectively. 注意,我添加了一些大写字母,以澄清发生了什么,如果你只分别使用小写字母ab而不是A / A_listB / B_list ,它也有效。

Sidenote 边注

I assume you do not get duplicate keys in the first level of dictionaries in the list. 我假设您没有在列表的第一级词典中获得重复键。 I think this is a correct assumption, since the required output would collapse these duplicate keys in the first level dictionaries. 我认为这是一个正确的假设,因为所需的输出会折叠第一级词典中的这些重复键。 Thus you can skip the list and use one dictionary instead of a list of dictionaries. 因此,您可以跳过列表并使用一个字典而不是字典列表。 This slightly simplifies the expressions. 这略微简化了表达式。 But depending on your application there might be even better (speak easier) ways to compare or/and combine two lists, dictionaries or sets. 但是根据您的应用程序,可能会有更好的(说起来更简单)方法来比较或/和组合两个列表,词典或集合。

A_dict = {'a':{'A':1}, 'b':{}}
B_dict = {'b': {'B': 1}, 'a': {'A': 0}}
dict_with_all_keys = {'a':{}, 'b':{}, 'c':{}}
# a dictionary solution with no list
new_dict = {k:{'A':(1 if k in A_dict and 'A' in A_dict[k] and A_dict[k]['A'] is 1 else 0), 
               'B':(1 if k in B_dict and 'B' in B_dict[k] and B_dict[k]['B'] is 1 else 0)} 
            for k in dict_with_all_keys}

A more readable way of doing it would be 一种更易读的方法就是这样做

a = [{'a':{'a':1}}, {'b':{'b':1}}, {'c':{}}]
b = [{'a':{'a':1,'b':0}}, {'b':{'a':1}}]

result = {}

for c in a + b:
    for key,value in c.items():
        result[key] = dict()
        result[key]['a'] = value.get('a', 0)
        result[key]['b'] = value.get('b', 0)

print(result)

Will give you answer 会给你答案
{'c': {'a': 0, 'b': 0}, 'a': {'a': 1, 'b': 0}, 'b': {'a': 1, 'b': 0}}

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

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