1

I have a dictionary:

my_dict = {
    "apples":"21",
    "vegetables":"30",
    "sesame":"45",
    "papaya":"18",
}

I want to generate a new one that will look like this:

my_dict = {
    "apples" : {"apples":"21"},
    "vegetables" : {"vegetables":"30"},
    "sesame" : {"sesame":"45"},
    "papaya" : {"papaya":"18"},
}

I wrote a code like this ....

my_dict = {
    "apples":"21",
    "vegetables":"30",
    "sesame":"45",
    "papaya":"18",
}

new_dict={}
new_value_for_dict={}

for key in my_dict:
    new_value_for_dict[key]= my_dict[key]
    new_dict[key]= new_value_for_dict
    # need to clear the last key,value of the "new_value_for_dict"

print(new_dict)

And the output comes as this:

{'vegitables':{'vegitables': '30', 'saseme': '45', 
               'apples': '21','papaya': '18'},
 'saseme':{'vegitables': '30', 'saseme': '45', 
           'apples': '21', 'papaya': '18'}, 
 'apples': {'vegitables': '30', 'saseme': '45', 
            'apples': '21', 'papaya': '18'}, 
 'papaya': {'vegitables': '30', 'saseme': '45', 
            'apples': '21', 'papaya': '18'}
}

But is not how I expected. How do eliminate the repetition ? How do I get it corrected ?

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130

2 Answers2

4

You could simply create a new dict with a comprehension:

>>> {k:{k:v} for k,v in my_dict.items()}
{'sesame': {'sesame': '45'}, 'vegetables': {'vegetables': '30'}, 'papaya': {'papaya': '18'}, 'apples': {'apples': '21'}}

I don't see any reason to do so, though. You don't get more information but it becomes harder to iterate over the dict values or retrieve information.

As mentioned by @AshwiniChaudhary in the comments, you could simply move new_value_for_dict={} inside the loop in order to recreate a new inner-dict at each iteration:

my_dict = {
    "apples":"21",
    "vegetables":"30",
    "sesame":"45",
    "papaya":"18",
}

new_dict={}

for key in my_dict:
    new_value_for_dict={}
    new_value_for_dict[key]= my_dict[key]
    new_dict[key]= new_value_for_dict

print(new_dict)
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
2

almost there

for key in my_dict:
...     my_dict[key]={key:my_dict.get(key)}
Eliethesaiyan
  • 2,327
  • 1
  • 22
  • 35