I want to declare a nested dictionary, with the key value pairs being a string and dict, with this nested dict having a key value pair of string and int). How would I go about doing this? Thanks!
Asked
Active
Viewed 324 times
-1
-
`defaultdict(dict)`? – Ch3steR Mar 25 '20 at 03:17
-
1Does this answer your question? [How do you create nested dict in Python?](https://stackoverflow.com/questions/16333296/how-do-you-create-nested-dict-in-python) – dspencer Mar 25 '20 at 03:22
-
What is the issue, exactly? Have you tried anything, done any research? – AMC Mar 25 '20 at 03:39
1 Answers
2
The same way as you make a regular dictionary, except put it inside another dictionary.
outer_dict = {
"inner1": {
"keyA": 1,
"keyB": 2,
"keyC": 3,
},
"inner2": {
"keyD": 4,
"keyE": 5,
"keyF": 6,
"keyG": 7,
},
}
If you wanted to annotate this with type hinting, you would do essentially the same thing, putting a Dict
inside another Dict
:
outer_dict: Dict[str, Dict[str, int]] = { ... }

Green Cloak Guy
- 23,793
- 4
- 33
- 53
-
3@mohammedwazeem The outer one is a dict. It has two keys: `"inner1"` and `"inner2"`. A set *would* also use curly brackets, but a set doesn't have keys (so, `{1, 2, 3}` would be a set, but `{1: 1, 2: 2, 3: 3}` would be a dict). If you try copypasting this code into a python console and to `type(outer_dict)`, it says `
`. – Green Cloak Guy Mar 25 '20 at 03:20 -
1hi thanks for the help, if I don't have any data to put in yet and just want to declare it i use the type hinting as you suggested? thanks! – mm21 Mar 25 '20 at 03:37
-
@mm21 If you're just declaring it then yes, that's how you would use type hinting. – Green Cloak Guy Mar 25 '20 at 03:38
-
sorry i am still confused, would I not do outer_dict = Dict[str, Dict[str, int]] – mm21 Mar 25 '20 at 03:41
-
-
sorry i mean to say initialize it, in C++ you would say map
outerdict , so I am trying to do this in python – mm21 Mar 25 '20 at 03:45 -
@mm21 As type hinting always goes, you can just declare a variable by doing `variablename: Type`, without assigning it to anything explicitly. Though it's probably a good idea to at least set it to whatever the "zero" or "empty" type. – Green Cloak Guy Mar 25 '20 at 03:48