Reputation: 791
I have a simple for loop
for m in my_list:
x = my_function(m)
my_dictionary = {m:x}
my_function()
gives me a string. And if I use print my_dictionary
at the end i get
{m1: string1}
{m2: string2}
I want to be able to have one dictionary at the end.
I have tried several methods that I found in other threads.
dic = dict(my_dictionary, **my_dictionary)
dic = my_dictionary.copy()
dic.update(my_dictionary)
But overtime I just get the last dictionary instead of all dictionaries.
I wish I could just add them with +
, but you can't do that in python
Upvotes: 1
Views: 93
Reputation: 180481
You can use a dict comprehension to create your main dict:
dic = {m : my_function(m) for m in my_list}
Upvotes: 3
Reputation: 4186
There is no need to recreate a new dictionnary at each loop iteration.
You can either create the dictionnary before and add items to it as you iterate:
my_dict = {}
for m in my_list:
my_dict[m] = my_function(m)
or you can use a dict comprehension:
my_dict = {m:my_function(m) for m in my_list}
or, in python 2:
my_dict = dict((m,my_function(m)) for m in my_list)
Upvotes: 1
Reputation: 1847
You can update the dictionary as opposed to overwrite it each time.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary.update({m:x})
print my_dictionary
Upvotes: 1
Reputation: 25414
Maybe I'm missing something, but isn't your problem just that you want a simple, non-nested dictionary, and you keep overwriting it within the loop? In that case, this small change should suffice:
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x
Upvotes: 1
Reputation: 599788
Why are you creating separate dictionaries in the first place? Just set the key in an existing dict on each iteration.
my_dictionary = {}
for m in my_list:
x = my_function(m)
my_dictionary[m] = x
Upvotes: 1