[英]Python, Merging dictionaries
I'm learning python and here I have a task.我正在学习 python 在这里我有一个任务。 I'm trying to figure out how can I merge dictionaries selecting them by one Key and update the remaining values.我试图弄清楚如何合并字典并通过一个键选择它们并更新剩余的值。 Here are the dictionaries:以下是词典:
the result i'm trying to obtain could be represented like this:我试图获得的结果可以这样表示:
I'm just beginning in programming, and this question could have a very evident solution, but i'm a bit confused trying to find it out我刚刚开始编程,这个问题可能有一个非常明显的解决方案,但我有点困惑试图找出它
thak you very much非常感谢你
I don't know if you want a bunch of variable names versus making a list, but in either case here's one possible way to do it:我不知道你是否想要一堆变量名而不是列出一个列表,但无论哪种情况,这里都有一种可能的方法:
act1= {'name': 'Max', 'day':1, 'payment (dollars)': 2}
act2= {'name': 'Tom', 'day':3, 'payment (dollars)': 5}
act3= {'name': 'Alison', 'day':2, 'payment (dollars)': 3}
act4= {'name': 'Pascal', 'day':3, 'payment (dollars)': 8}
act5= {'name': 'Tom', 'day':7, 'payment (dollars)': 6}
act6= {'name': 'Max', 'day':2, 'payment (dollars)': 1}
act7= {'name': 'Tom', 'day':8, 'payment (dollars)': 8}
# make variables into list for easier handling (or just start with one, hopefully)
def take_act_vars_to_list():
global_vars = globals()
act_list = []
for num in range(1, 8): # this is hardcoded, but could be inferred
key_now = "act" + str(num)
assert(key_now in global_vars) # check that the variable exists
act_list.append(global_vars[key_now])
return act_list
# merge and update dictionary elements
def update_dict(dict_to_update, reference_dict):
# update dictionary from the duplicate references
for key in reference_dict:
if key is not "name":
if key in dict_to_update:
dict_to_update[key] += reference_dict[key]
else: # make new key and entry
dict_to_update[key] = reference_dict[key]
return
act_list = take_act_vars_to_list()
merged_vars = {}
for dict_now in act_list: # iterate over dictionary entries
name_now = dict_now["name"] # want to merge based on name
if name_now not in merged_vars: # initialize a new dictionary
merged_vars[name_now] = {}
update_dict(merged_vars[name_now], dict_now)
else: # update existing dictionary
sub_dict = merged_vars[name_now]
update_dict(sub_dict, dict_now)
For this example the result of merged_vars is对于这个例子,merged_vars 的结果是
{'Max': {'day': 3, 'payment (dollars)': 3}, 'Tom': {'day': 18, 'payment (dollars)': 19}, 'Alison': {'day': 2, 'payment (dollars)': 3}, 'Pascal': {'day': 3, 'payment (dollars)': 8}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.