Python - 将字典与优先级结合起来
有时,在处理字典数据时,我们可能会遇到需要合并两个字典的问题。这是很常见的问题。但是这种方法的一种变体可以是组合字典,如果字典中的两个键发生冲突,则优先考虑特定的字典。让我们讨论可以执行此任务的某些方式。
Input : test_dict1 = {‘Gfg’ : 6, ‘is’ : 15, ‘best’ : 13}
test_dict2 = {‘Gfg’ : 8, ‘is’ : 10}
Output : {‘Gfg’: 8, ‘best’: 13, ‘is’: 10}
Input : test_dict1 = {‘Gfg’ : 6}
test_dict2 = {‘Gfg’ : 8}
Output : {‘Gfg’: 8}
方法 #1:使用copy()
+ 循环
上述功能的组合可以用来解决这个问题。这是可以解决此问题的粗暴方式。在此,我们执行 copy() 以深度复制字典值,然后使用优先级字典覆盖这些值。
# Python3 code to demonstrate working of
# Combine dictionary with priority
# Using loop + copy()
# initializing dictionaries
test_dict1 = {'Gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'Gfg' : 4, 'is' : 10, 'for' : 7, 'geeks' : 12}
# printing original dictionaries
print("The original dictionary is 1 : " + str(test_dict1))
print("The original dictionary is 2 : " + str(test_dict2))
# declaring priority order
prio_dict = {1 : test_dict2, 2: test_dict1}
# Combine dictionary with priority
# Using loop + copy()
res = prio_dict[2].copy()
for key, val in prio_dict[1].items():
res[key] = val
# printing result
print("The dictionary after combination : " + str(res))
The original dictionary is 1 : {‘is’: 2, ‘best’: 3, ‘Gfg’: 1}
The original dictionary is 2 : {‘for’: 7, ‘is’: 10, ‘geeks’: 12, ‘Gfg’: 4}
The dictionary after combination : {‘for’: 7, ‘is’: 10, ‘best’: 3, ‘geeks’: 12, ‘Gfg’: 4}
方法 #2:使用** operator
这是解决这个问题的一种新方法,我们可以绑定两个字典,第二位绑定的字典优先于初始字典的键。
# Python3 code to demonstrate working of
# Combine dictionary with priority
# Using ** operator
# initializing dictionaries
test_dict1 = {'Gfg' : 1, 'is' : 2, 'best' : 3}
test_dict2 = {'Gfg' : 4, 'is' : 10, 'for' : 7, 'geeks' : 12}
# printing original dictionaries
print("The original dictionary is 1 : " + str(test_dict1))
print("The original dictionary is 2 : " + str(test_dict2))
# declaring priority order
prio_dict = {1 : test_dict2, 2: test_dict1}
# Combine dictionary with priority
# Using ** operator
res = {**prio_dict[2], **prio_dict[1]}
# printing result
print("The dictionary after combination : " + str(res))
The original dictionary is 1 : {‘is’: 2, ‘best’: 3, ‘Gfg’: 1}
The original dictionary is 2 : {‘for’: 7, ‘is’: 10, ‘geeks’: 12, ‘Gfg’: 4}
The dictionary after combination : {‘for’: 7, ‘is’: 10, ‘best’: 3, ‘geeks’: 12, ‘Gfg’: 4}