Home > Back-end >  Can't append all values to dictionary using for loop
Can't append all values to dictionary using for loop

Time:08-17

I want to append some values in a list to a dictionary but its only appending the last one

Code:

l = [(1,2),(3,4)]
a = {}
for i in l:
        a['r'] = [i]
print(a)

Ouput:

{'r': [(3,4)]}

Ouput i want:

{'r': [(1,2),(3,4)]}

CodePudding user response:

try this

l = [(1,2),(3,4)]
a = {}
a['r'] = []
for i in l:
        a['r'].append(i)
print(a)

or simply you can do

l = [(1,2),(3,4)]
a = {}
a['r'] = l

print(a)

this is the output

{'r': [(1, 2), (3, 4)]}

CodePudding user response:

More general solution using setdefault:

l = [(1, 2), (3, 4)]
a = {}
for i in l:
    a.setdefault('r', []).append(i)
print(a)

Output:

{'r': [(1, 2), (3, 4)]}

CodePudding user response:

I would use a defaultdict from the standard library collections module

from collections import defaultdict

a = defaultdict(list)

l = [(1,2),(3,4)]
for i in l:
        a['r'].append(i)
print(a)
  • Related