Python 3,添加两个词典,并在与键相关联的列表中添加项,两个词典都有

时间:2018-04-12 15:55:55

标签: python python-3.x list numpy dictionary

我有很长的工作/小时名单,但是会根据地点给出。

例如:

捐赠:位置,名称,MON,TUES,WED,THURS,FRI

for rows in  data:
    print(rows)

打印:

"location_1", "name_1", "0.0","0.0","0.0","4.1","2.2"
"location_2", "name_1", "8.0","8.0","8.0","0.0","3.0"
"location_1", "name_2", "8.4","7.3","7.2","4.0","2.0"
"location_1", "name_3", "7.0","7.0","5.0","6.0","3.0"

如果您注意到前两行具有相同的名称但位置不同,我想通过添加它们的值将它们组合成一个dict。 我可以把它们变成像这样的字典。 (注意name_1以及如何修改)

location_1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
             "name_2":["8.4","7.3","7.2","4.0","2.0"],
             "name_3":["7.0","7.0","5.0","6.0","3.0"]}

location_2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

但我需要通过添加与具有相同名称的键相关联的列表的值来添加两个词典。所以结果应该是这样的(注意name_1的最后一个值以及上一个dict的最后一个值是如何添加的):

result_dict = {"name_1":["8.0","8.0","8.0","4.1","5.2"],
               "name_2":["8.4","7.3","7.2","4.0","2.0"],
               "name_3":["7.0","7.0","5.0","6.0","3.0"]}

我是Python的新手,所以如果有人能告诉我一个有效的方法,那就太好了。 谢谢。

2 个答案:

答案 0 :(得分:1)

如果您对使用第三方库感到满意,可以使用numpy轻松完成此操作。

我故意以数字形式保存输出。最好将数字数据存储在数字类型中。

import numpy as np

d1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
     "name_2":["8.4","7.3","7.2","4.0","2.0"],
     "name_3":["7.0","7.0","5.0","6.0","3.0"]}

d2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

res = {k: np.array(d1.get(k, [0]*5), dtype=float) + \
          np.array(d2.get(k, [0]*5), dtype=float) \
       for k in d1.keys() | d2.keys()}

# {'name_1': array([ 8. ,  8. ,  8. ,  4.1,  5.2]),
#  'name_2': array([ 8.4,  7.3,  7.2,  4. ,  2. ]),
#  'name_3': array([ 7.,  7.,  5.,  6.,  3.])}

答案 1 :(得分:1)

此解决方案不需要任何外部库,因此如果您不熟悉Python,可能会更容易。

location_1= {"name_1":["0.0","0.0","0.0","4.1","2.2"],
                       "name_2":["8.4","7.3","7.2","4.0","2.0"],
                       "name_3":["7.0","7.0","5.0","6.0","3.0"]}
location_2 = {"name_1":["8.0","8.0","8.0","0.0","3.0"]}

for key, value in location_2.items():
    if key not in location_1:
        location_1[key] = value
    else:
        for i in range(len(value)):  # each index in the list
            old = location_1[key][i]
            new = float(old)+float(value[i])
            location_1[key][i] = str(new)  # str optional

最后,该值将转换回字符串,但我建议将其保留为数值。

此外,浮点数存储浮点数,可以有小数位,如果您不熟悉常规编码,则可以将其作为数字而不是字符串进行操作。要将值保留为float,请替换最后一行

    location_1[key][i] = str(new)

    location_1[key][i] = new