Dictionary Merge vs List Merge in Python

foreword

It's time to share Python tips every day. Today, I will share with you two common data type merging methods in Python. Curious to know what it is? don't tell

Tell you, if you want to know, look down. Without further ado, let's go straight to...
insert image description here

1 Merge dictionaries

In some scenarios, we need to merge two (multiple) dictionaries. For example, the following two dictionaries need to be merged:

1 dict1 = {
    
    "a": 2, "b": 3, "c": 5}
2 dict2 = {
    
    "a": 1, "c": 3, "d": 8}

And the combined result is:

1 {
    
    'c': 8, 'd': 8, 'a': 3, 'b': 3}

So how should it be done? Since two dictionaries cannot be added directly, each dictionary needs to be converted into a Counter class first, and then added. The specific code is as follows:

Python学习交流Q群:906715085####
1 from collections import Counter
2 dict1 = {
    
    "a": 2, "b": 3, "c": 5}
3 dict2 = {
    
    "a": 1, "c": 3, "d": 8}
4 result = Counter({
    
    })
5 for item in [dict1,dict2]:
6     result += Counter(item)
7 print(result) # Counter({'c': 8, 'd': 8, 'a': 3, 'b': 3})

Of course, if it's just adding two dictionaries, it's just one line of code:

1 result = Counter(dict1) + Counter(dict2)

insert image description here

2 Merge lists

In some cases, we need to merge two (multiple) lists to get a dictionary containing the frequency of each element. For example, you need to combine the following two lists:

1 a = ["天", "之", "道", "损", "有", "余", "而", "补", "不", "足"]
2 b = ["人", "之", "道", "损", "不", "足", "而", "补", "有", "余"]

Combined as:

1 Counter({
    
    '之': 2, '道': 2, '损': 2, '有': 2, '余': 2, '而': 2, '补': 2, '不': 2, '足': 2, '天': 1, '人': 1})

Then you only need to do it with the following code:

1 from collections import Counter
2 counter = Counter()
3 for item in [a, b]:
4     counter.update(item)
5 print(counter)

Of course, in addition to using this method when constructing a vocabulary, this method can also be used when searching for or counting duplicate elements in a list.

At last

I hope the little skills shared today can be helpful to you when you are learning, remember to collect them and learn them slowly. Like and follow, more skills can be mastered in real time, if you don't understand, remember to like

Comments, I usually answer.

insert image description here

Guess you like

Origin blog.csdn.net/xff123456_/article/details/124450316