1

I am new to python and very new to using types. I have some function that returns a dictionary where the key is a string and value is a list of strings. I want to know what is the correct way to express this using types.

Sample output

{"lebron": ["king","goat","bron"], "jordan": ["clutch", "goat", "bulls"]}

Code

from typing import Any, Dict, List

def foo_bar() -> Dict[str, Any]:
    my_map: Dict[str, Any] = {}
    # some stuff happens
    return my_map


def foo_bar() -> Dict[str, List[str]]:
    my_map: Dict[str, List[str]] = {}
    # some stuff happens
    return my_map

I have posted two approaches one is more specific which is Dict[str, List[str]] but i have never seen anyone use this anywhere so i am not sure if it is correct.

Sluna
  • 169
  • 10
  • I'm not sure whether this question should be edited for clarity or deleted altogether but, please, see: [Why is "Is this correct?" an off-topic question, and what should I ask instead?](https://meta.stackoverflow.com/q/359466) – Georgy Dec 09 '20 at 16:34

3 Answers3

2

Yes, both type annotations are correct. You should prefer to use Dict[str, List[str]] for being more specific.

Addendum: specificity is preferable in this situation, in other cases generality might be more preferable.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
  • makes sense for instance if i was returning a dictionary where i have str as key and list of str has value in some cases and str has value in other cases then i would use `Any` right – Sluna Dec 02 '20 at 13:18
  • You might, or you might use `Dict[str, Union[List[str], str]]`, or, say `Dict[str, Sequence[str]]`, depending on your needs. – Jasmijn Dec 02 '20 at 17:11
  • what does union indicate? – Sluna Dec 02 '20 at 23:36
  • `Union[A, B]` represents values with a type of either `A` or `B`. Check out the documentation for [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union). – Jasmijn Dec 03 '20 at 09:29
2

No need to follow the ancient way of defining variables in python. Python itself take care of data types. Just do

a = dict()

or

a = {}

and then

a["mylist1"] = ["item1", "item2"]
b["mylist2"] = ["item1", "item2"]

But what methods you have posted are also correct.

rdsquare
  • 41
  • 4
1

Firstly define the function which takes string and value. In second line initiate dictionary. In third step you can directly start assigning values to the key.

def foo_bar(string, val):
    my_map = dict()
    my_map[string] = val 
    return my_map

In this case string is the key and val is the value

So in your case

my_map = dict()
my_map["lebron"] = ["king","goat","bron"]
my_map["jordan"]: ["clutch", "goat", "bulls"]
print(my_map)

It must give desired output.

Anuj Karn
  • 42
  • 5