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
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.
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.
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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With