Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending values to dictionary in for loop

Tags:

python

Just cant get this working. Any help is highly appreciated.

dict = {}
for n in n1:
    if # condition #
        dict[key] = []
        dict[key].append(value)
        print dict

This is printing something like this

{'k1':['v1']} and {'k1':['v2']}

I have few other nested for loops down this code, which will be using this dict and the dict has only the latest key value pairs i.e. {'k1':'v2'}

I am looking for something like {'k1':['v1','v2']}

Please suggest a solution without using setdefault

like image 317
Krishna Chaitanya Avatar asked Feb 01 '17 02:02

Krishna Chaitanya


People also ask

How do you add a value to a loop in a dictionary?

To add key-value pairs to a dictionary within a loop, we can create two lists that will store the keys and values of our dictionary. Next, assuming that the ith key is meant for the ith value, we can iterate over the two lists together and add values to their respective keys inside the dictionary.

Can you append values to a dictionary?

Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.

Can we append values in dictionary Python?

Method 1: Using += sign on a key with an empty value In this method, we will use the += operator to append a list into the dictionary, for this we will take a dictionary and then add elements as a list into the dictionary.


3 Answers

You can also check key existence before assign.

dict = {}
for n in n1:
    if # condition #
        if key not in dict:
            dict[key] = []
        dict[key].append(value)
        print dict
like image 54
gzc Avatar answered Oct 20 '22 09:10

gzc


Give collections.defaultdict a try:

#example below is in the docs.
from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

print(sorted(d.items()))
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

the d = defaultdict(list) line is setting the keys values to be an empty dictionary by default and appending the value to the list in the loop.

like image 34
Back2Basics Avatar answered Oct 20 '22 09:10

Back2Basics


The problem with the code is it creates an empty list for 'key' each time the for loop runs. You need just one improvement in the code:

dict = {}
dict[key] = []
for n in n1:
   if # condition #
       dict[key].append(value)
       print dict
like image 3
deepika Avatar answered Oct 20 '22 09:10

deepika