Sluna
Sluna

Reputation: 189

Using defaultdict to append to list of strings

Background

I am new to python and using types. I am basically trying to use defaultdict to populate a dictionary that contains a string as key and values which are List of strings.

Code

from typing import DefaultDict, List
from collections import defaultdict

my_dict: DefaultDict[str, List[str]] = defaultdict(List[str])

my_dict["Lebron"] = "goat"
my_dict["Lebron"] = "king"

print(my_dict)

My current output is defaultdict(typing.List[str], {'Lebron': 'king'}) i expect it to be defaultdict(typing.List[str], {'Lebron': ['goat','king']}) instead.

Issue if i change my code to use append like this i get an error

from typing import DefaultDict, List
from collections import defaultdict

my_dict: DefaultDict[str, List[str]] = defaultdict(List[str])

my_dict["Lebron"].append("goat")
my_dict["Lebron"].append("king")

print(my_dict)

Error

    raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead

Upvotes: 0

Views: 2367

Answers (2)

ssp
ssp

Reputation: 1710

As @juanpa.arrivillaga has already mentioned, List[str] is just type annotation.

Use

my_dict: DefaultDict[str, List[str]] = defaultdict(list)

And go the append route.

Upvotes: 3

Mighty Diffy
Mighty Diffy

Reputation: 98

You should try this:

from typing import DefaultDict, List
from collections import defaultdict

my_dict: DefaultDict[str, List[str]] = defaultdict(List[str])

my_dict["Lebron"] = ["goat", "king"]

print(my_dict)

Upvotes: 1

Related Questions