--I want to combine multiple dictionaries into one dictionary ――I want to add other elements as well
dictA = {'A1': 1, 'A2': 1}
dictB = {'B1': 1, 'B2': 1}
# ---(Combine dictionaries&Add element)---
# => {'key1': 1, 'key2': 1, 'A1': 1, 'A2': 1, 'B1': 1, 'B2': 1}
further,
--I want to process it non-destructively (without making any changes to the original dictionary) --Do not change the value (I want an error if the key is duplicated)
I would like to introduce an efficient writing method to realize these.
This is partly possible with ``` .update ()` `` and additional dictionary notation.
dictA.update(dictB)
dictA['key1'] = 1
dictA['key2'] = 1
new_dict = dictA
print(new_dict)
# => {'A1': 1, 'A2': 1, 'B1': 1, 'B2': 1, 'key1': 1, 'key2': 1}
The original dictA is gone. (Because of adding elements (destructive changes) to dictA)
print(dictA)
# => {'A1': 1, 'A2': 1, 'B1': 1, 'B2': 1, 'key1': 1, 'key2': 1}
Also, if the key is duplicated, the value will be overwritten. This can cause unintended behavior (causing bugs).
dictA = {'key': 'dictA'}
dictB = {'key': 'dictB'}
dictA.update(dictB)
print(dictA)
# => {'key': 'dictB'}
Create a new dictionary by passing values to the keyword arguments of the dict function without worrying about joining or adding elements. Any number is possible.
new_dict = dict(
key1=1,
key2=1,
**dictA,
**dictB,
)
print(new_dict)
# => {'key1': 1, 'key2': 1, 'A1': 1, 'A2': 1, 'B1': 1, 'B2': 1}
The original dictionary is unchanged because it is a non-destructive process.
new_dict['keyA1'] = 5
print(new_dict['keyA1'])
# => 5
print(dictA['keyA1'])
# => 1
If there are duplicates, a TypeError will occur, so you can avoid overwriting unintended values. An error will occur for duplicate keys in the dictionary and all explicitly written keyword arguments.
dictA = {'key': 'dictA'}
dictB = {'key': 'dictB'}
new_dict = dict(
key='A',
**dictA,
**dictB,
)
# => TypeError: type object got multiple values for keyword argument 'key'
It was said that if you recreate it with the dict function, you can combine dictionaries and add elements safely and concisely!
Recommended Posts