current position:Home>[Python daily homework] Day7: how to combine two dictionaries in an expression?

[Python daily homework] Day7: how to combine two dictionaries in an expression?

2022-01-30 10:51:10 Bug play programming

Hello everyone , I am a bug, A normal programmer .

The rapid growth of programmers , It's about practicing , More output , Share more , Multiple links .

But the execution is too poor , Missed a lot of good opportunities .

It's not too late to start , Welcome to pay attention , Witness the growth of an ordinary programmer .

Let's set up a Flag, To participate in Brother Tao talks Python Technology circle Clock in the daily homework of knowledge planet , Hold on first 7 God .

problem :

Day7 Q18: How to combine two dictionaries in an expression ?

solve :

Go straight to the code :

# Q18:  How to combine two dictionaries in an expression ?

a = {"a": 1, "b": 2, "c": 3}
b = {"b": 1, "e": 2, "f": 3}


# 1.  Multiline expressions merge two dictionaries , And does not affect the original dictionary 
def dict_merge(dict_a, dict_b):
    result = dict_a.copy()
    result.update(dict_b)
    return result


print(dict_merge(a, b))

# 2  adopt  list  Merge two dictionaries 
print(dict(list(a.items()) + list(b.items())))

# 3. Python 3.4  After version ,PEP 478
print({**a, **b})

# 4.  Direct updating  a  Dictionaries 
a.update(b)
print(a)

#  Running results 
# {'a': 1, 'b': 1, 'c': 3, 'e': 2, 'f': 3}
# {'a': 1, 'b': 1, 'c': 3, 'e': 2, 'f': 3}
# {'a': 1, 'b': 1, 'c': 3, 'e': 2, 'f': 3}
# {'a': 1, 'b': 1, 'c': 3, 'e': 2, 'f': 3}
 Copy code 

summary :

Okay ,Day7 Clock out is over , To study the python in , Dictionary merge operation .

If you are also learning Python , Welcome and bug Communicate together .

Official account bug Play programming , Play programming together !

copyright notice
author[Bug play programming],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301051095690.html

Random recommended