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}
CodePudding user response:
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.
CodePudding user response:
You can use update
to append the key and values in the dictionary as follows:
frigo = {"mangue": 2, "orange": 8, "cassoulet": 1, "thon": 2, "coca": 8, "fenouil": 1, "lait": 3}
new_frigo = {}
for (key, value) in frigo.items():
new_frigo.update({key:value})
print(new_frigo)
Result:
{'mangue': 2, 'orange': 8, 'cassoulet': 1, 'thon': 2, 'coca': 8, 'fenouil': 1, 'lait': 3}