Search code examples
pythondictionarystrong-typing

How to create a new typing.Dict[str,str] and add items to it


There is a great Q/A here already for creating an untyped dictionary in Python. I'm struggling to figure out how to create a typed dictionary and then add things to it.

An example of what I am trying to do would be...

return_value = Dict[str,str]
for item in some_other_list:
  if item.property1 > 9:
    return_value.update(item.name, "d'oh")
return return_value

... but this gets me an error of descriptor 'update' requires a 'dict' object but received a 'str'

I've tried a few other permutations of the above declaration

return_value:Dict[str,str] = None

errors with 'NoneType' object has no attribute 'update'. And trying

return_value:Dict[str,str] = dict() 

or

return_value:Dict[str,str] = {}

both error with update expected at most 1 arguments, got 2. I do not know what is needed here to create an empty typed dictionary like I would in C# (var d = new Dictionary<string, string>();). I would rather not eschew type safety if possible. What am I missing or doing incorrectly?


Solution

  • The last 2 ones are the right usage of Dict, but you updated the dictionary with incorrect syntax inside the for loop.

    return_value: Dict[str, str] = dict()
    for item in some_other_list:
        if item.property1 > 9:
            return_value[item.name] = "d'oh"
    return return_value