Python通过键将多个值附加到嵌套字典

Python通过键将多个值附加到嵌套字典,python,dictionary,Python,Dictionary,我试图通过键向嵌套字典添加另一个值,我有下面的代码,但它不能正常工作 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.stri

我试图通过键向嵌套字典添加另一个值,我有下面的代码,但它不能正常工作

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'}   

我做错了什么?

你不太了解
update
does;是的,不是附加的。请尝试以下方法:

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

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

如果要保留
子字段的顺序,请使用
OrderedDict

您不太了解的
更新
操作;是的,不是附加的。请尝试以下方法:

if a not in dict:
    dict.update({a: {'Value1': b, 'Value2': c, 'Value3': d}},)
else:
   dict[a]['Value1'] += ',' + b
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'}}
输出:

a {'Value3': 'd', 'Value2': 'c', 'Value1': 'b,b,b'}
如果要保留
子字段的顺序,请使用
OrderedDict

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(“,”)


这应该是你的窍门。你必须在else语句中添加“,”,因为你在使用
split(“,”)时删除了它。

请在你的问题中添加
content
的内容。这没什么大不了的,但你可能可以在line.split()]中为x编写
a,b,c,d=[x.strip()][/code>,这样看起来更像python:)@Ding
.split(“,”)
*如果有帮助,我已经添加了内容。我也会对split做一些修改,试着在你的问题中添加
content
的内容。没什么大不了的,但是你可以在line.split()中为x编写
a,b,c,d=[x.strip()][/code>,这样看起来更像python:)@Ding
.split(',)
*如果有帮助的话,我已经添加了内容。我还将对split进行更改,并尝试
dict[a]['Value1']+=b