6

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?

GCien
  • 1,819
  • 4
  • 25
  • 51
  • you can directly give like this : `dict[some_variables_name1] = value1` right ? – Vikas P Feb 02 '18 at 11:32
  • @VikasDamodar Yeh, and I want `value1` to be a further nesting of data... – GCien Feb 02 '18 at 11:34
  • 2
    So can you mention any sample o/p you are expecting ? – Vikas P Feb 02 '18 at 11:35
  • 1
    Possible duplicate of [Python dictionary key error when assigning - how do I get around this?](https://stackoverflow.com/questions/24089383/python-dictionary-key-error-when-assigning-how-do-i-get-around-this) – Aran-Fey Feb 02 '18 at 11:36
  • 1
    You can define your `dict = defaultdict(list)` instead of `dict = {}` – Abdul Niyas P M Feb 02 '18 at 11:40
  • You may find useful [setdefault](https://docs.python.org/3/library/stdtypes.html#dict.setdefault) method of `dict`. – Georgy Feb 02 '18 at 11:42
  • @MichaelRobers, as per above comment I've included `defaultdict` method below. – jpp Feb 02 '18 at 12:38

6 Answers6

4

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})
jpp
  • 134,728
  • 29
  • 196
  • 240
3

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 Biyani
  • 5,322
  • 7
  • 32
  • 48
3

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

serkef
  • 289
  • 2
  • 12
3

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.

Banana
  • 1,071
  • 4
  • 20
1

to create a new dictionary use:

dict = dict()

When you try to add something you use:

+=

There is nothing to add. you have to first create the value

dict[some_variables_name1] = [{ 'key1': value1 }]

As also suggested do not use dict.. a simple d that means dict is the way forward.

johnashu
  • 2,101
  • 2
  • 14
  • 34
  • 1
    @johnashu Hi, yeh didn't quite work. Thank you tho (I didn't downvote) – GCien Feb 02 '18 at 11:34
  • 1
    @johnashu Your amending suggestion worked. Of course, it doesn't exist so can't `+=` to it just need to set it with `=`. Stupid! Will accept as correct answer when I can. Thank you. – GCien Feb 02 '18 at 11:38
0

If the dictionary is of only one pair of key and value, I found using dictionary zip can be handy (beforehand collected all keys and values in separate lists and than zip them to construct a new dictionary which like adding those dictionaries).

Here my example

" I want to make {c} = {{a}, {b}}"

c = { }
a = {"100": "1.1"}
b = {"200": "1.2"}

# d and e just dummies
d = [ ]
e = [ ]
for item in [a, b]:
    d += list(item)
    e += list(item.values())

c = dict(zip(d,e))
print(c)

"  c  = {'100': '1.1', '200': '1.2'} “
KokoEfraim
  • 108
  • 7
  • Sorry, I just found dictionary update even more handy ``` c = { } a = {"100": "1.1"} b = {"200": "1.2", "300":"1.3"} c.update(a) c.update(b) c "{'100': '1.1', '200': '1.2', '300': '1.3'}" ``` – KokoEfraim Jul 21 '20 at 09:35