Ali89
Ali89

Reputation: 87

Putting a dictionary inside a dictionary?

Lets say we have

{'Pop': 5}

and we have a variable

a = 'store'

how could I get the output:

{'store': {'pop': 5}}

Is there a easy way?

Upvotes: 0

Views: 561

Answers (4)

cnavarreteliz
cnavarreteliz

Reputation: 139

I think that your best option is,

a = 'store'
temp = {}
temp[a] = {'Pop': 5}

print(temp)

regards!

Upvotes: 0

Denziloe
Denziloe

Reputation: 8162

dict1 = {'pop': 5}
dict2 = {'store': dict1}
print(dict2)

This will work. If you tried to do dict2['store'] = dict1 immediately, it wouldn't have worked, because dict2 needs to exist before you can say "put stuff in dict2". An alternate approach would have been:

dict1 = {'pop': 5}
dict2 = {}    # making an empty dictionary
dict2['store'] = dict1    # now we can put stuff in it
print(dict2)

Upvotes: 3

Neil
Neil

Reputation: 14321

It is very simple. You can even assign values normally.

print({'store': {'pop': 5}})

temp = {}
temp['score']  = {'pop':5}
print(temp)

Upvotes: 0

Craig
Craig

Reputation: 4855

You can put a dictionary inside a dictionary.

Try it:

print({a:{'pop':5}})

Upvotes: 0

Related Questions