0

I have a dictionary as follow:

d1 = {1:"Peter", 2:"Teddy"}

I want to make it to:

d1 = {1:"Peter", 2:"Teddy", 3:{"Oliver" : "Big"}}

I have tried but it doesn't work:

d1[3]["Oliver"]="Big"
Yokanishaa
  • 75
  • 5
  • 2
    Precede with `d1[3] = {}` – jarmod Nov 04 '22 at 17:53
  • 3
    or `d1[3] = {"Oliver" : "Big"}` – quamrana Nov 04 '22 at 17:54
  • if the key `1` may or may not exist with a dictionary already, and you don't want to overwrite it, but add another key to the existing dictionary already there, then use: `d1.setdefault(3, {})['Oliver'] = 'big'` – juanpa.arrivillaga Nov 04 '22 at 18:08
  • possible duplicate https://stackoverflow.com/questions/16333296/how-do-you-create-nested-dict-in-python There is also lots of information about nested dictionaries online. – Sterling Nov 04 '22 at 18:11

2 Answers2

3

Try

d1[3] = {"Oliver": "Big"}
Jedi
  • 3,088
  • 2
  • 28
  • 47
0

You can first try

d1[3] = {}

Then

d1[3]["Oliver"]="Big"
Andromeda
  • 1,205
  • 1
  • 14
  • 21