在Python中比较由具有唯一键的字典组成的两个列表

jecbmhm3  于 2023-06-28  发布在  Python
关注(0)|答案(7)|浏览(135)

我有两个列表,两者都包含相同数量的字典。每个字典都有一个唯一的键。第二列表中的第一列表的每个字典都存在匹配,即在另一列表中存在具有唯一键的字典。但是这两个词典的其他元素可以变化。例如:

list_1 = [
            {
                'unique_id': '001',
                'key1': 'AAA',
                'key2': 'BBB',
                'key3': 'EEE'
             },
             {
                'unique_id': '002',
                'key1': 'AAA',
                'key2': 'CCC',
                'key3': 'FFF'
             }
         ]

 list_2 = [
             {
                'unique_id': '001',
                'key1': 'AAA',
                'key2': 'DDD',
                'key3': 'EEE'
             },
             {
                'unique_id': '002',
                'key1': 'AAA',
                'key2': 'CCC',
                'key3': 'FFF'
             }
         ]

我想比较2个匹配字典的所有元素。如果任何元素不相等,我想打印不相等的元素。
你能帮帮忙吗?

ryhaxcpt

ryhaxcpt1#

假设字典像你的示例输入一样排成一行,你可以使用zip()函数来获得一个关联字典对的列表,然后你可以使用any()来检查是否有差异:

>>> list_1 = [{'unique_id':'001', 'key1':'AAA', 'key2':'BBB', 'key3':'EEE'}, 
              {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
>>> list_2 = [{'unique_id':'001', 'key1':'AAA', 'key2':'DDD', 'key3':'EEE'},
              {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
>>> pairs = zip(list_1, list_2)
>>> any(x != y for x, y in pairs)
True

或者得到不同的对:

>>> [(x, y) for x, y in pairs if x != y]
[({'key3': 'EEE', 'key2': 'BBB', 'key1': 'AAA', 'unique_id': '001'}, {'key3': 'EEE', 'key2': 'DDD', 'key1': 'AAA', 'unique_id': '001'})]

你甚至可以得到每对不匹配的密钥:

>>> [[k for k in x if x[k] != y[k]] for x, y in pairs if x != y]
[['key2']]

可能与相关值一起:

>>> [[(k, x[k], y[k]) for k in x if x[k] != y[k]] for x, y in pairs if x != y]
[[('key2', 'BBB', 'DDD')]]

**注意:**如果您的输入列表尚未排序,您也可以轻松完成:

>>> from operator import itemgetter
>>> list_1, list_2 = [sorted(l, key=itemgetter('unique_id')) 
                      for l in (list_1, list_2)]
xytpbqjk

xytpbqjk2#

最快和最全面的方法是,使用两个setstuples

set_list1 = set(tuple(sorted(d.items())) for d in sorted(list1))
set_list2 = set(tuple(sorted(d.items())) for d in sorted(list2))

(if您的列表已经是sorted,只需删除列表排序以保存性能)
使用intersection查找重叠

set_overlapping = set_list1.intersection(set_list2)

使用symmetric_difference查找差异

set_difference = set_list1.symmetric_difference(set_list2)

tuple转换回dict

for tuple_element in set_difference:
     list_dicts_difference.append(dict((x, y) for x, y in tuple_element))
q35jwt9p

q35jwt9p3#

以下代码比较字典并打印不相等的项:

for d1, d2 in zip(list_1, list_2):
    for key, value in d1.items():
        if value != d2[key]:
            print key, value, d2[key]

输出:key2 BBB DDD。通过使用zip,我们可以一次遍历两个字典。然后,我们遍历第一个字典的条目,并将该值与第二个字典中的相应值进行比较。如果这两个值不相等,那么我们将打印键和这两个值。

wnavrhmk

wnavrhmk4#

我有一个实际上不依赖于特定键的版本,所以元素是相等的(零)或不相等的(非零):

list_1 = [{'unique_id':'001', 'key1':'AAA', 'key2':'BBB', 'key3':'EEE'}, {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
list_2 = [{'unique_id':'001', 'key1':'AAA', 'key2':'DDD', 'key3':'EEE'}, {'unique_id':'002', 'key1':'AAA', 'key2':'CCC', 'key3':'FFF'}]
list_3 = [{'Name': 'Abid', 'Age': 27},{'Name': 'Mahnaz', 'Age': 27}]
list_4 = [{'Name': 'Abid', 'Age': 27},{'Name': 'Mahnaz', 'Age': 27}]

print cmp(list_1,list_1)
print cmp(list_1,list_3)
print cmp(list_1,list_2)
print cmp(list_2,list_1)
print cmp(list_3,list_4)

给出:

Return Value :  0
Return Value :  1
Return Value : -1
Return Value :  1
Return Value :  0
5cg8jx4n

5cg8jx4n5#

Let list1 = []
list2 = []

To fetch all the key values we can do like this:
key_values = list1[0]
key = key_values.keys() //key is a list and contains all key values

below is a piece of code which compares all the key pair values:

for val in list1:
    first_key = key[0]
    for val2 in list2:
        if val2[first_key] == val[first_key]:
            for val3 in key:
                if val2[val3] != val[val3]:
                    Unmatched.append(val)

print unmatched

Above contains matches dictionary and prints for which all key, pair values didn't match.
arknldoa

arknldoa6#

def new_change(old_list, new_list):
    change_list = []
    for x in new_list:
        for y in old_list:
            if x['unique_id'] != y['unique_id']:
                change_list.append(x)
    return change_list

在此方法的一侧传递旧列表和新列表

vbopmzt1

vbopmzt17#

根据键值比较两个字典列表,并从另一个字典列表中得到不同的字典项::-------

db_items = [
{
    "id": "db...1111",
    "name": "amit",
    "type": "cricket",
    "value": "kumar"
},
{
    "id": "db...222",
    "name": "rishabh",
    "type": "traveller",
    "value": "gupta"
},
{
    "id": "items.....2222",
    "name": "raj",
    "type": "foodie",
    "value": "ankur"
}
]
items = [
{
    "id": "items.....1111",
    "name": "abhishek",
    "type": "cricket",
    "value": "sharma"
},
{
    "id": "items.....2222",
    "name": "hardik",
    "type": "traveller",
    "value": "sharma"
},
{
    "id": "db...333",
    "name": "shanchay",
    "type": "music",
    "value": "kumar"
}
]
for item in items.copy():
for i in db_items:
    if item.get("type") == i.get("type"):
        items.remove(item)

print(items)

output:---
[{'id': 'db...333', 'name': 'shanchay', 'type': 'music', 'value': 
'kumar'}]

相关问题