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?
return_value
isn't adict
; it's an object that represents the type of adict
. The things you import fromtyping
are only for type hints, not actual values. – Grizeldamypy
. – Acknowledgedict
, you domy_dict[key] = value
..update
takes another mapping, e.g. another dict, and updates the key-value pairs in the mapping you pass as an argument. So you could domy_dict.update({key:value})
but that is rather wasteful for a single item(creating a completely unnecessary intermediate dict object). Alternatively, you can pass keyword arguments to.update
, like so:my_dict.update(foo='bar', baz='bing')
which sometimes is nice from a readability perspective – Acknowledge