How can I add a list's items to a key in a dictionary with already existing values?

Viewed 1007

I'm trying to add my list's items to a dictionary as extra values of all the keys.

The dictionary and list look like this:

mydic = {'1':22, '2':33, '3':44}
mylist = [23,24,25]

I want my dictionary to look like this:

mydic = {'1': [22, 23], '2': [33,24], '3': [44,25]}

My idea that's not working since "AttributeError: 'tuple' object has no attribute 'add'" was this:

for item in mylist:
       for k in mydic.items():
           mydic[k].append(item)

What's a better way to put the list's items inside the dictionary?

7 Answers

I used the enumerate function. It returns a variable that starts with 0 and the item of the list.

Here, I took the dictionary and reassigned it at each key to be a list of the previous value and the new item.

for i, item in enumerate(mylist):
    mydic[str(i+1)]=[mydic[str(i+1)], item]

Source: https://docs.python.org/3/library/functions.html#enumerate

for i,(k,v) in enumerate(mydic.items()):
    mydic[k]=[v,mylist[i]]

Iterate over the dictionary keys by index of the keys, and assign a list to each value of the dictionary.

mydic = {'1':22, '2':33, '3':44}
mylist = [23, 24, 25]

mykeys = list(mydic.keys())
for idx in range(len(mylist)):
    mydic[mykeys[idx]] = [mydic[mykeys[idx]], mylist[idx]]

print(mydic)
# {'1': [22, 23], '2': [33, 24], '3': [44, 25]}

This works fine.

count = 0
for x in mydic.items():
    mydic[x[0]] = [mydic[x[0]]]
    mydic[x[0]].append(mylist[count])
    count += 1
print(mydic)

You can do it like this:

mydic = {'1':22, '2':33, '3':44}
mylist = [23,24,25]

mydic = {k: [v1, v2] for (k,v1), v2 in zip(mydic.items(),mylist)}

Firstly, when you iterate for k in mydic.items() you are actually getting a tuple containing (key, value). That's why the Tuple error is occurring. Instead, by using for key, value in mydic.items() we can get rid of that error. However, your double iteration meants that every single element is being added to each key in the dict. To avoid this, we can do the following:

for key, value in mydic.items():
    mydic[key].append(mylist[key-1])
mydict = {'1':22, '2':33, '3':44}
mylist = [23,24,25]
for key, value in mydict.items():
    mydict[key] = [value, mylist[int(key)-1]]
Related