且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-19 17:30:14

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(',')