43
votes

Possible Duplicate:
syntax to insert one list into another list in python

How could be the syntax for creating a dictionary into another dictionary in python

3
What tutorial are you using to learn Python? - S.Lott
possible duplicate of syntax to insert one list into another list in python (Yes, I completely understand that lists are not dictionaries, but it's like the same question again with different words. What's next, creating tuples inside tuples?) - Greg Hewgill
furthermore, it's by the same user. You would think one example would be enough. - aaronasterling
I was interpreting this question more in the sense of cloning a dict, which has nothing to do with the linked "duplicate" question. Also note that the accepted answer in the "duplicate" question uses append and definitely cannot by applied here. - bluenote10
A list is not a dictionary, the question that the link says is duplicated is not the same at all - peterretief

3 Answers

106
votes

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
9
votes
dict1 = {}

dict1['dict2'] = {}

print dict1

>>> {'dict2': {},}

this is commonly known as nesting iterators into other iterators I think

3
votes

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']