簡體   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}}]

在這里,我有兩個字典列表。 我想比較這些並生成一個這樣的新列表:

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然后是[{'a': {'B': 0, 'A': 0}}, {'b': {'B': 0, 'A': 0}}, {'c': {'B': 0, 'A': 0}}]

注意,我添加了一些大寫字母,以澄清發生了什么,如果你只分別使用小寫字母ab而不是A / A_listB / B_list ,它也有效。

邊注

我假設您沒有在列表的第一級詞典中獲得重復鍵。 我認為這是一個正確的假設,因為所需的輸出會折疊第一級詞典中的這些重復鍵。 因此,您可以跳過列表並使用一個字典而不是字典列表。 這略微簡化了表達式。 但是根據您的應用程序,可能會有更好的(說起來更簡單)方法來比較或/和組合兩個列表,詞典或集合。

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 = [{'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)

會給你答案
{'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