Python typing dict of dicts

Question:

How do I correctly type hint this python structure:

people={ 
   "john" : {"likes": "apples", "dislikes": "organges"},
   "aisha": {"likes": "kittens", "dislikes": "ravens"}
}

EDIT: There can be any keys specified – e.g. "mary","joseph", "carl"…
I understand that the value-dict can be typed as such

class _Preferences(TypedDict):
    likes: str
    dislikes: str

But I am not sure how to type the people dict itself.

Asked By: Konrads

||

Answers:

people: dict[str, dict[str, str]] = { 
   "john": {"likes": "apples", "dislikes": "oranges"},
   "aisha": {"likes": "kittens", "dislikes": "ravens"}
}

This should work on the newer versions of python3

Answered By: jalwan

You can define a TypedDict for the values and then annotate the people dictionary with it:

from typing import TypedDict


class LikesDislikes(TypedDict):
    likes: str
    dislikes: str


people: dict[str, LikesDislikes]

people = {
    "john": {"likes": "apples", "dislikes": "organges"},
    "aisha": {"likes": "kittens", "dislikes": "ravens"},
}

Your people dictionary doesn’t have a fixed structure, but they are strings. You can’t do much more about it. If it has fixed structure you could write it as a TypedDict too and set LikesDislikes as the keys’ values. like:

class People(TypedDict):
    john: LikesDislikes
    aisha: LikesDislikes

But it doesn’t make sense here.

Answered By: S.B