Python - adding key value parts to empty dict

The pythonic solution is to set default values for your dictionary. In my opinion, collections.defaultdict is the best option for this.

Also, please do not use variables names which are also classes. I have called the dictionary d below.

from collections import defaultdict

d = defaultdict(list)

some_variables_name1 = str(some_variable1)
d[some_variables_name1].append({'key1': value1})

some_variables_name2 = str(some_variable2)
d[some_variables_name2].append({'key2': value2})

you have to first check is "foo" present in dictionary as a key.

You can try:

if "foo" in dict_name:
    dict_name.append("new_append")
else:
    dict_name["foo"] = ["first entry"]

Small suggestion: do not use dict as dictionary variable as it is keyword in Python


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