Skip to content

Dict

You can declare a CLI parameter to be a standard Python dict:

import typer
from typing_extensions import Annotated


def main(user_info: Annotated[dict, typer.Option()] = {}):
    print(f"Name: {user_info.get('name', 'Unknown')}")
    print(f"User attributes: {sorted(user_info.keys())}")


if __name__ == "__main__":
    typer.run(main)
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

import typer


def main(user_info: dict = typer.Option({})):
    print(f"Name: {user_info.get('name', 'Unknown')}")
    print(f"User attributes: {sorted(user_info.keys())}")


if __name__ == "__main__":
    typer.run(main)

Check it:

// Run your program
$ python main.py --user-info '{"name": "Camila", "age": 15, "height": 1.7, "female": true}'

Name: Camila
User attributes: ['age', 'female', 'height', 'name']

This can be particularly useful when you want to include JSON input:

import json

data = json.loads(user_input)