[英]how append (key,value) with loop on python
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.我想创建一个带有循环的新字典,但我找不到使用 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}
There's already a python function for that:已经有一个 python function :
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
. dict.update(other_dict)
只是将other_dict
的所有内容添加到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.在这里使用
i
没有意义 - 字典new_frigo
没有索引,但有键。
You can use update
to append the key and values in the dictionary as follows:您可以使用
update
append 字典中的键和值如下:
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()):
new_frigo.update({key:value})
print(new_frigo)
Result:结果:
{'mangue': 2, 'orange': 8, 'cassoulet': 1, 'thon': 2, 'coca': 8, 'fenouil': 1, 'lait': 3}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.