[英]Python append multiple values to nested dictionary by key
我正在嘗試通過鍵將另一個值添加到嵌套字典中,我有以下代碼,但無法正常工作
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
確實不太了解。 它是替換 ,而不是追加。 試試這個,代替:
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'}
如果要保留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'}}
這應該可以解決問題。 您必須在else語句中添加',',因為在使用split(',')
時將其刪除了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.