Creating a dictionary in a list from known variables

73 views Asked by At

I have some known values/variables a,b,c,d.

I would like to use these variables to create a dictionary in a list. I did the following but it did not work:

nestedlist['Name'] = a
nestedlist['Address']['StreetNumber'] = b
nestedlist['Address']['Zipcode']=c
nestedlist['Email']=d

I am getting the following error:

Traceback (most recent call last):
    nestedlist['Address']['StreetNumber'] = b
    KeyError: 'Address'

What am I missing here?

4

There are 4 answers

2
James Sapam On BEST ANSWER

Before you do:

nestedlist['Address']['StreetNumber'] = b
nestedlist['Address']['Zipcode']=c

Do, this to create dictionary with key Address

nestedlist.setdefault("Address", dict())

# http://code.activestate.com/recipes/66516-add-an-entry-to-a-dictionary-unless-the-entry-is-a/

After that you can add key, value:

nestedlist['Address']['StreetNumber'] = b
nestedlist['Address']['Zipcode']=c
0
Nilesh On

You have to create dict,

nestedlist = {"name":None, "Address": {}, "Email": None}

Then you can assign Address

You are trying to assing b to Address's StreetNumber key.

But Address is not exist, so it gives KeyError

0
Eli On

Use a defaultdict:

from collections import defaultdict
blah = defaultdict(dict)
blah['Address']['Zipcode']=c
0
Mazdak On

Firs of all its dictionary not list because if it was a list you'll get an IndexError.dictionary just create one key with assignment like :

>>> d={}
>>> d['a']=2
>>> d
{'a': 2}

And for create nested dictionary the value of preceding key should be defined as a dictionary so far!

>>> d['b']={}
>>> d['b']['c']=6
>>> d
{'a': 2, 'b': {'c': 6}}

Along side the other answers that suggests defaultdict and setdefault you can also create a nested dictionary with dict comprehension :

>>> d={i:j if i!='b' else {'c':j} for i,j in [('b',4),('a',1),('d',3)]}
>>> d
{'a': 1, 'b': {'c': 4}, 'd': 3}