xxxxxxxxxx
# merge two dictionaries
a = {'apple':1, 'melon': 4}
b = {'apple': 2, 'orange': 2,'banana':3}
merge_dic = {**a, **b}
print(merge_dic) # {'apple': 2, 'melon': 4, 'orange': 2, 'banana': 3}
#Python 3.9:
# a|b
xxxxxxxxxx
d1 = {'name': 'Alex', 'age': 25}
d2 = {'name': 'Alex', 'city': 'New York'}
merged_dict = {**d1, **d2}
print(merged_dict) # {'name': 'Alex', 'age': 25, 'city': 'New York'}
xxxxxxxxxx
>>> dict_a = {'a': 1, 'b': 2}
>>> dict_b = {'b': 3, 'c': 4}
>>> dict_c = {**dict_a, **dict_b}
>>> dict_c
# {'a': 1, 'b': 3, 'c': 4}
xxxxxxxxxx
# Python 3.9
z = x | y
# Python 3.5
z = {**x, **y}
# Python <= 3.4
def merge_two_dicts(x, y):
z = x.copy() # start with keys and values of x
z.update(y) # modifies z with keys and values of y
return z
z = merge_two_dicts(x, y)
xxxxxxxxxx
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
xxxxxxxxxx
foreach (var item in custom_settings)
{
default_settings[item.Key] = item.Value;
}
xxxxxxxxxx
# merge two dictionaries
x = {'a': 1,'b':2}
y = {'d':3,'c':5}
z = {**x, **y}
print(z) # {'a': 1, 'b': 2, 'd': 3, 'c': 5}
xxxxxxxxxx
public static Dictionary<TKey, HashSet<T>> Merge<TKey, T>(this Dictionary<TKey, HashSet<T>> destination, Dictionary<TKey, HashSet<T>> source)
{
if (destination.Count == 0)
{
destination.AddRange(source);
return destination;
}
if (source.Count == 0)
return destination;
foreach (var keyValuePair in source)
{
if (destination.Keys.Contains(keyValuePair.Key))
destination[keyValuePair.Key].UnionWith(keyValuePair.Value);
else
destination.Add(keyValuePair.Key, keyValuePair.Value);
}
return destination;
}
xxxxxxxxxx
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)
xxxxxxxxxx
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print({**dict_1, **dict_2})
xxxxxxxxxx
yusuke_power = {"Yusuke Urameshi": "Spirit Gun"}
hiei_power = {"Hiei": "Jagan Eye"}
powers = dict()
# Brute force
for dictionary in (yusuke_power, hiei_power):
for key, value in dictionary.items():
powers[key] = value
# Dictionary Comprehension
powers = {key: value for d in (yusuke_power, hiei_power) for key, value in d.items()}
# Copy and update
powers = yusuke_power.copy()
powers.update(hiei_power)
# Dictionary unpacking (Python 3.5+)
powers = {**yusuke_power, **hiei_power}
# Backwards compatible function for any number of dicts
def merge_dicts(*dicts: dict):
merged_dict = dict()
for dictionary in dicts:
merge_dict.update(dictionary)
return merged_dict