简体   繁体   English

append(键,值)如何在 python 上使用循环

[英]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.

相关问题 如何在循环中将第二个值附加到字典中的现有键 - How to Append a 2nd value to an existing key in a dictionary in Python in a Loop 如何将新键添加到现有字典并将前一个键作为值附加到 for 循环中创建的新键:python - How to add a new key to an existing dictionary and append previous key as value to the new key created in a for loop : python 如何在python字典中的同一个键上附加一个值? - How to append a value on the same key in dictionary of python? 如何在Python dict的值前附加键? - How to append a key before a value in Python dict? Python3:我如何 append 多个键、值对到 for 循环中的字典? - Python3: How do I append multiple key,value pairs to a dictionary in for loop? 如何在 python 中使用循环 append - How to append with loop in python 如何使用管道定界符将值附加到python中的相同键 - How to append value to the same key in python using pipe delimiter 如果使用Python在Postgres中主键或ID相同,如何附加值 - How to append value if Primary key or id is same in postgres using python 我如何将 append 与所需值相对应的键添加到 Python 中的列表? - How do I append a key that corresponds with a wanted value to a list in Python? 如何使用python将多个键和值附加到嵌套字典中? - How to append multiple key and value into a nested dictionary using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM