AK9309
AK9309

Reputation: 791

Joining dictionaries in a for loop

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

Answers (5)

Padraic Cunningham
Padraic Cunningham

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

301_Moved_Permanently
301_Moved_Permanently

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

Sahil M
Sahil M

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

Joel Hinz
Joel Hinz

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

Daniel Roseman
Daniel Roseman

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

Related Questions