Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - adding key value parts to empty dict

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?

like image 365
GCien Avatar asked Feb 02 '18 11:02

GCien


2 Answers

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.

like image 132
Banana Avatar answered Oct 10 '22 20:10

Banana


@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.

like image 26
serkef Avatar answered Oct 10 '22 21:10

serkef