Joey
Joey

Reputation: 3

Appending additional values to existing keys of a dictionary in for loop in python

I have a dictionary dic = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0} and I would like to append values to these existing keys as an array after each loop without overwriting the existing values. Like this:

list = [......]
keys_set = list(range(10))
dic = {key: 0 for key in keys_set} 

for index in range(len(data)):
    condition = list[index].numpy()
    for x in (condition):
        for key in keys_set:
            if x == key:
                dic[key].append[index]

But I get the error AttributeError: 'int' object has no attribute 'append' I have tried (extend, append, update) but they do not work. I would expect to return something that looks like this:

{0: ([24121,  4849, 40312, ...,  8343, 17503, 15662]), 
1: ([25202, 37384, 53119, ..., 42502, 11939, 54489]), 
2: ([47883, 45099,  6391, ..., 17220, 45904,  1735]), 
3: ([36057, 24066, 36887, ...,  2587, 36021, 39961]), 
4: ([23270, 45773, 10778, ..., 33301, 55598, 53125]), 
5: ([40253, 30402, 24574, ..., 37823, 53769, 51425]), 
6: ([48568,  4923,  1986, ...,  6178, 27890, 39086]), 
7: ([35919, 36136, 38468, ..., 39877, 31991, 24692]), 
8: ([23147, 40398,  1745, ..., 16440, 40957, 53170]), 
9: ([ 3785,   583, 15312, ..., 42293, 58852, 46889])}

Upvotes: 0

Views: 387

Answers (1)

Erik McKelvey
Erik McKelvey

Reputation: 1627

You need to make the values in your dictionary lists:

keys_set = list(range(10))
dic = {key: [] for key in keys_set} 

for index in range(len(data)):
    condition = list[index].numpy()
    for x in (condition):
        for key in keys_set:
            if x == key:
                dic[key].append[index]

Upvotes: 1

Related Questions