1

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

AK9309
  • 731
  • 3
  • 13
  • 32

5 Answers5

3

You can use a dict comprehension to create your main dict:

dic = {m : my_function(m) for m in my_list}
Community
  • 1
  • 1
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
1

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
Daniel Roseman
  • 567,968
  • 59
  • 825
  • 842
1

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
Joel Hinz
  • 23,685
  • 6
  • 57
  • 74
1

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
Sahil M
  • 1,713
  • 1
  • 15
  • 30
1

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)
301_Moved_Permanently
  • 3,818
  • 12
  • 26