Python programming merges based on the values of the same key in the dictionary list

  • 2021-12-05 06:34:25
  • OfStack

Table of Contents 1. Preface the data of the two lists are: expected merge results 2. Implementation analysis 3. Summary

1. Preface

Today, a fan asked a question. He now has two lists, both of which are dictionaries, and each dictionary has one key Is id, and now I want to merge these two dictionaries into one dictionary according to id, with the following effect:

The data for the two lists are:


a_list = [{'id': 1, 'value': 11}, {'id': 2, 'value': 22}, {'id': 3, 'value': 33}]
b_list = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]

Expect the result of the merger


[{'id': 1, 'name': 'a', 'value': 11},
 {'id': 2, 'name': 'b', 'value': 22},
 {'id': 3, 'name': 'c', 'value': 33}]

2. Implement analysis

This is the implementation code written by fans:


for i in range(len(b_list)):
    for a in a_list:
        if b_list[i]['id'] == a['id']:
            b_list[i]['value'] = a['value']
print(b_list)

Through two for loops, the a_list Element dictionary in id Value is equal to b_list Element field id Value is added to the corresponding b_list Element dictionary.

In fact, two lines of code can solve this problem:

1. We can first derive the a_list Reassemble as {id:value} Form of


a_values = {a['id']: a['value'] for a in a_list}

The values for a_values are:


{1: 11, 2: 22, 3: 33}

2. Then, the value is compared with the value by derivation and dictionary deconstruction and then merging b_list Reassemble:


res_list = [{**b, **{'value': a_values[b['id']]}} for b in b_list]

The assembled list value is


res_list The value of is:  
[{'id': 1, 'name': 'a', 'value': 11},
 {'id': 2, 'name': 'b', 'value': 22}, 
 {'id': 3, 'name': 'c', 'value': 33}]

Complete sample code


a_list = [{'id': 1, 'value': 11}, {'id': 2, 'value': 22}, {'id': 3, 'value': 33}]
b_list = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]
a_values = {a['id']: a['value'] for a in a_list}
res_list = [{**b, **{'value': a_values[b['id']]}} for b in b_list]
print('res_list The value of is: ', res_list)

Of course, one line of code can also be done, and the two deductions can be merged directly


res_list = [{**b, **{'value': {a['id']: a['value'] for a in a_list}[b['id']]}} for b in b_list]

But this is to install X and write code, there is no need!

3. Summary

Is the derivation and dictionary through ** Deconstruction to merge these two knowledge points.

The above is the Python Learning Dictionary list according to the value of the same key merging details, more information about the Python Dictionary list key merging please pay attention to other related articles on this site!


Related articles: