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
Solution 1:
You don't quite understand with update
does; it's replacement, not appending. Try this, instead:
if a notindict:
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
.
Solution 2:
dictionary = {}
forlinein 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(',')
Post a Comment for "Python Append Multiple Values To Nested Dictionary By Key"