0

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?

6
  • Please add the content of content to your question. Commented Jun 16, 2017 at 16:11
  • Not a big deal, but you can probably write a, b, c, d = [x.strip() for x in line.split()] so it looks more pythonic :) Commented Jun 16, 2017 at 16:12
  • @Ding .split(',')* Commented Jun 16, 2017 at 16:15
  • I've added content if it helps. I'll make changes to split as well Commented Jun 16, 2017 at 16:18
  • Try dict[a]['Value1'] += b Commented Jun 16, 2017 at 16:21

2 Answers 2

2

You don't quite understand with update does; 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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.