I've created a dictionary instance without any key: value pairs, standard
dict = {}
I'm then returning back some information from an API to be added to this dictionary dependent on some variables name.
some_variables_name1 = str(some_variable1)
dict[some_variables_name1] += [{ 'key1': value1 }]
some_variables_name2 = str(some_variable2)
dict[some_variables_name2] += [{ 'key2': value2 }]
However, I seem to be getting an error similar to this *Assuming that str(some_variable1) is equal to 'foo'
:
KeyError: 'foo'
Any pro tips?
Other answers already adressed why this fails, here is a convenient solution that sets a default for if the key is not already present, such that your appending does not fail. The way I read it, you want a dictionary with lists of other dictionaries as values. Imagining a situation such as
somedict = {}
somevar = 0
somevar_name = str(somevar)
key1 = "oh"
value1 = 1
You can do
somedict.setdefault(somevar_name,[]).append({key1,value1})
This will evaluate to
{'0': [{'oh', 1}]}
In other words, change lines of this sort
somedict[some_variables_name] += [{ 'somekey': somevalue }]
Into:
somedict.setdefault(some_variables_name,[]).append({'somekey':somevalue})
I hope this answers your question.
@Harsha is right.
This:
dict[some_variables_name1] += [{ 'key1': value1 }]
Will do:
dict[some_variables_name1] = dict[some_variables_name1] + [{ 'key1': value1 }]
Right-Hand-Side needs to be evaluated first so, it will try to lookup:
dict[some_variables_name1]
Which will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With