-1

So i am simply trying to append my list containing a set of numbers, to a value in a dictionary which is currently a list.

I don't know whether it is important but some of the lists in the dictionary are empty and some contain integers.

I assumed this would be simple and tried the most obvious thing to me which was appending the list to that value like this.

middlenumberdic[y].append(numberlist)

However this gave me the following error:

    middlenumberdic[y].append(numberlist)
KeyError: 786

So i decided that the problem was that lists couldn't apppend with lists so i broke it up into individual integers

for value in numberlist:
    middlenumberdic[y].append(value)

but this just gave me the same KeyError thing

    middlenumberdic[y].append(value)
KeyError: 792

From my point of view i would've thought that middlenumberdic[y] would return [123,456,789] (as that is what is assigned to it) and then that i could just append to that list but apparently i can't.

Before doing all this i tried middlenumberdic[y] = numberlistand although this didn't result in an error all it did was overwrite my existing list rather than adding to it.


After reading How to append to a list in a dictionary? and Append to a list within a dictionary i was still none the wiser which is why i have posted this.

For the first question the answer given was much the same as the solution i used which didn't work and the other question was to complicated for me to understand.

This is my first question i've asked on this site so i'm sorry if i've done something wrong.

P.S Their is more script but i thought only this would be neccesary

Community
  • 1
  • 1
Joe Clinton
  • 155
  • 9

2 Answers2

1

Your problem is not with the appending part. It's with accessing your list in the dictionary. The KeyError means there are not elements with index 786 or 792.

In [1]: a = dict()

In [2]: a[5] = []

In [3]: a
Out[3]: {5: []}

In [4]: a[5]
Out[4]: []

In [5]: a[5].append([3,4,5])

In [6]: a
Out[6]: {5: [[3, 4, 5]]}
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
0

I think you are trying to access with a key that doesn't exist. So, you are getting this KeyError. In that case,

for value in numberlist:
     middlenumberdic[y].append(value)

Replace this with below:

for value in numberlist:
    middlenumberdic.setdefault(y,[]).append(value)

I think it should work now.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • Thankyou, this worked perfectly. it seems that i had not intialized the dictionary with empty values. – Joe Clinton Jan 31 '16 at 12:21
  • Yes, you are right. What `setdefault(key,[])` does is, if it couldn't find the key, it initializes the key with an empty list. Only then you can append some value to it. – Ahsanul Haque Jan 31 '16 at 12:26