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
  • 761
  • 3
  • 13
  • 33

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
  • 176,452
  • 29
  • 245
  • 321
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
  • 588,541
  • 66
  • 880
  • 895
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
  • 24,719
  • 6
  • 62
  • 75
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,790
  • 1
  • 16
  • 31
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
  • 4,007
  • 14
  • 28