Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 dictionary with known keys typing

I'm using Python 3 typing feature for better autocomplete.

Many times I have functions that return key/value (dictionary) with specific keys. super simple example:

def get_info(name):     name_first_letter = name[0]     return {'my_name': name, 'first_letter': name_first_letter} 

I want to add type hinting to this function to tell others who use this function what to expect.

I can do something like:

 class NameInfo(object):      def __init__(self, name, first_letter):          self.name = name          self.first_letter = first_letter 

and then change the function signature to:

def get_info(name) -> NameInfo: 

But it requires too much code for each dictionary.

What is the best practice in that case?

like image 265
Idok Avatar asked May 28 '17 09:05

Idok


People also ask

What are the supported types for Python 3 dict () keys?

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

What is a typed dict?

A TypedDict type represents dictionary objects with a specific set of string keys, and with specific value types for each valid key. Each string key can be either required (it must be present) or non-required (it doesn't need to exist).

Can dictionary store any data type?

The keys of a dictionary can be any kind of immutable type, which includes: strings, numbers, and tuples: mydict = {"hello": "world", 0: "a", 1: "b", "2": "not a number" (1, 2, 3): "a tuple!"}

Can I index a key of dictionary Python?

Python dictionary index of keyBy using list(*args) with a dictionary it will return a collection of the keys. We can easily use the index to access the required key from the method and convert it to a list. In this example to use the list[index] function and it will return the key at index in the list.


1 Answers

As pointed out by Blckknght, you and Stanislav Ivanov in the comments, you can use NamedTuple:

from typing import NamedTuple   class NameInfo(NamedTuple):     name: str     first_letter: str   def get_info(name: str) -> NameInfo:     return NameInfo(name=name, first_letter=name[0]) 

Starting from Python 3.8 you can use TypedDict which is more similar to what you want:

from typing import TypedDict   class NameInfo(TypedDict):     name: str     first_letter: str   def get_info(name: str) -> NameInfo:     return {'name': name, 'first_letter': name[0]} 
like image 101
4 revs, 3 users 90% Avatar answered Oct 08 '22 17:10

4 revs, 3 users 90%