简体   繁体   中英

Compare and add new key in dict using list Comprehension in Python

I am trying to compare two lists of dicts by key = 'TABLE' and if the value of 'TABLE' is the same in both dicts then I need to subtract values of 'MB'.

list1 = [{'TABLE':'A', 'MB':110, 'INFO':'No'}, {'TABLE':'B', 'MB':200, 'INFO':'YES'}]
list2 = [{'TABLE':'A', 'MB':101, 'INFO':'No'}, {'TABLE':'B', 'MB':220, 'INFO':'YES'}]

Result I want to add in the first list of dict adding a new key = 'DIFF'. Diff I found but I have no idea how to add new key/value inside of list Comprehension in my case.

diff = [[item['MB'] - table['MB']] for table in list1 for item in list2 if item['TABLE'] == table['TABLE']]

My expectation is to get list1 as below:

list1 = [{'TABLE':'A', 'MB':110, 'INFO':'No', 'DIFF': -9}, {'TABLE':'B', 'MB':200, 'INFO':'YES', 'DIFF':20}]

Thanks in advance.

You can use double for-loops as:

for d1 in list1:
    for d2 in list2:
        if d1['TABLE'] == d2['TABLE']:
            d1['DIFF'] = d2['MB'] - d1['MB']

Output:

>>> print(list1)
[{'TABLE': 'A', 'MB': 110, 'INFO': 'No', 'DIFF': -9},
 {'TABLE': 'B', 'MB': 200, 'INFO': 'YES', 'DIFF': 20}]

Is there a specific reason to use a list comprehension for this task. For me this is much cleaner written as a nested for loop. Its easier to read and avoids using side effects inside list comprehensions.

list1 = [{'TABLE':'A', 'MB':110, 'INFO':'No'}, {'TABLE':'B', 'MB':200, 'INFO':'YES'}]
list2 = [{'TABLE':'A', 'MB':101, 'INFO':'No'}, {'TABLE':'B', 'MB':220, 'INFO':'YES'}]
diff = [[item['MB'] - table['MB']] for table in list1 for item in list2 if item['TABLE'] == table['TABLE']]
for l1 in list1:
    for l2 in list2:
        if l1['TABLE'] == l2['TABLE']:
            l1['DIFF'] = l1['MB'] - l2['MB']
print(f"{list1=}")

OUTPUT

list1=[{'TABLE': 'A', 'MB': 110, 'INFO': 'No', 'DIFF': 9}, {'TABLE': 'B', 'MB': 200, 'INFO': 'YES', 'DIFF': -20}]

Here's a marginally more efficient double loop approach. This avoids looking up the TABLE value from list1 more times than is necessary:

list1 = [{'TABLE':'A', 'MB':110, 'INFO':'No'}, {'TABLE':'B', 'MB':200, 'INFO':'YES'}]
list2 = [{'TABLE':'A', 'MB':101, 'INFO':'No'}, {'TABLE':'B', 'MB':220, 'INFO':'YES'}]

for d1 in list1:
    v1 = d1['TABLE']
    for d2 in list2:
        if (v2 := d2['TABLE']) == v1:
            d1['DIFF'] = d2['MB'] - d1['MB']
print(list1)

If either the TABLE or MB keys are missing from any of the dictionaries, this will fail with KeyError.

Output:

[{'TABLE': 'A', 'MB': 110, 'INFO': 'No', 'DIFF': -9}, {'TABLE': 'B', 'MB': 200, 'INFO': 'YES', 'DIFF': 20}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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