Can't append all values to dictionary using for loop

Question:

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)]}

Asked By: Zen35X

||

Answers:

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)]}
Answered By: Harsh Gupta

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)]}
Answered By: funnydman

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)
Answered By: el_oso
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.