Thursday, May 12, 2022

[FIXED] how append (key,value) with loop on python

Issue

I want to create a new dict with a loop but I don't find the way to push key and value in loop with append. I try something like this but I'm still searching the good way.

frigo = {"mangue" : 2, "orange" : 8, "cassoulet" : 1, "thon" : 2, "coca" : 8, "fenouil" : 1, "lait" : 3}
new_frigo  = {} 

for i, (key, value) in enumerate(frigo.items()):
    print(i, key, value)
    new_frigo[i].append{key,value}

Solution

There's already a python function for that:

new_frigo.update(frigo)

No need for a loop! dict.update(other_dict) just goes and adds all content of the other_dict to the dict.

Anyway, if you wanted for some reason to do it with a loop,

for key, value in frigo.items():
  new_frigo[key] = value

would do that. Using an i here makes no sense - a dictionary new_frigo doesn't have indices, but keys.



Answered By - Marcus Müller
Answer Checked By - Terry (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.