简体   繁体   中英

How to declare a nested dictionary in Python?

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!

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]] = { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM