[英]Python append multiple values to nested dictionary by key
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)
I want it to look like: 我希望它看起来像:
a {'Value1': 'b,b,b', 'Value2': 'c', 'Value3': 'd'}
What am I doing wrong? 我究竟做错了什么?
You don't quite understand with update
does; 您对
update
确实不太了解。 it's replacement , not appending. 它是替换 ,而不是追加。 Try this, instead:
试试这个,代替:
if a not in dict:
dict.update({a: {'Value1': b, 'Value2': c, 'Value3': d}},)
else:
dict[a]['Value1'] += ',' + b
Output: 输出:
a {'Value3': 'd', 'Value2': 'c', 'Value1': 'b,b,b'}
If you want to preserve the order of the Value
sub-fields, then use an OrderedDict
. 如果要保留
Value
子字段的顺序,请使用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'}}
This should do your trick. 这应该可以解决问题。 You gotta add the ',' in the else statement because you removed it when you used
split(',')
您必须在else语句中添加',',因为在使用
split(',')
时将其删除了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.