0

So I'm trying to create a nested dictionary but I can't seem to wrap my head around the logic.

So say I have input coming in from a csv:

1,2,3
2,3,4
1,4,5

Now'd like to create a dictionary as follows:

d ={1:{2:3,4:5}, 2:{3:4}}

Such that for the first being some ID column that we create keys in the sub dictionary corresponding to second value.

The way I tried it was to go:

d[row[0]] = {row[1]:row[2]}

But that overwrites the first instead of appending/pushing to it, how would I go about this problem? I can't seem to wrap my mind around what keys to use.

Any guidance is appreciated.

2
  • 2
    dict overwrites a builtin function. Pick a different name for your dictionary. dict[row[0]] = ... just overwrites the existing object with a new one. If it exists, add a new property on it. Commented Aug 7, 2019 at 22:18
  • Should've been more clear, I just wrote that example. I'll change the name. Commented Aug 7, 2019 at 22:19

3 Answers 3

2

Yes, cause dict[row[0]] = is dict[1] = what overwrites previous dict[1] value You should use :

dict.setdefault(row[0],{})[row[1]] = row[2]

remember there must be no duplicates for row[1] then

or

dict.setdefault(row[0],{}).update({row[1]:row[2]})
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know about set default that was what I was looking for. Thank you!
oh yes and you should not call the valiable dict cause it overwrites the dict type
0
if dict[row[0]] == None:
    dict[row[0]] = {row[1]:row[2]}
else:
    dict[row[0]][row[1]] = row[2]

1 Comment

No need for == None (switch the statements in the blocks), and it's best practice to use is None if you do need to compare against None. Correct answer though, thanks!
0

you can use defaultdict, which is similaire to the built-in dictionaries, but will create dictionaries with a default values, in your case a default value will be a dictionary

from collections import  defaultdict
res = defaultdict(dict)

with this code we are creating a defaultdict, with it's values default value being of type dict, so next we would do

for row in l:
    res[row[0]][row[1]] = row[2]

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.