Python通过键将多个值附加到嵌套字典 [英] Python append multiple values to nested dictionary by key

查看:52
本文介绍了Python通过键将多个值附加到嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过键将另一个值添加到嵌套字典中,我具有以下代码,但无法正常工作

I am trying to add another value to a nested dictionary by key, I have the below code but it doesn't work properly

Content is a file with:
a,b,c,d
a,b,c,d
a,b,c,d

dict   = {}

for line in content:
    values = line.split(",")
    a = str.strip(values[0])
    b = str.strip(values[1])
    c = str.strip(values[2])
    d = str.strip(values[3])

    if a not in dict:
        dict.update({a: {'Value1': b, 'Value2': c, 'Value3': d}},)
    else:
       dict[a]['Value1'].update(b)

我希望它看起来像:

a {'Value1': 'b,b,b', 'Value2': 'c', 'Value3': 'd'}   

我在做什么错了?

推荐答案

dictionary = {}

for line in content: 
  values = line.split(",")
  a = str.strip(values[0])
  b = str.strip(values[1])
  c = str.strip(values[2])
  d = str.strip(values[3])

  if a not in dictionary.keys():
      dictionary = {a: {'Value1': b, 'Value2': c, 'Value3': d}} # creates dictionary
  else:
      dictionary[a]['Value1'] += ','+b # accesses desired value and updates it with ",b"
print(dictionary)
#Output: {'a': {'Value1': 'b,b,b', 'Value2': 'c', 'Value3': 'd'}}

这应该可以解决问题.您必须在else语句中添加',',因为使用 split(',')

This should do your trick. You gotta add the ',' in the else statement because you removed it when you used split(',')

这篇关于Python通过键将多个值附加到嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆