简体   繁体   English

Python3:我如何 append 多个键、值对到 for 循环中的字典?

[英]Python3: How do I append multiple key,value pairs to a dictionary in for loop?

I want to append key, value pairs to my empty dictionary.我想将 append 键、值对添加到我的空字典中。

I can succeed with one object but not multiple:我可以成功使用一个 object 但不是多个:

a[key] = [value]

My code returns error 'TypeError: update expected at most 1 arguments, got 2' - Is it possible to pass the key, values as variables?我的代码返回错误'TypeError: update expected at most 1 arguments, got 2' - 是否可以将键、值作为变量传递?

dict = {"Avv": 33333, "Animal": 22, "color": 12, "location": 40000000}

a = {}

for key, value in dict.items():
    if key.startswith("A"):
        a.update(key, value)
    else:
        #does something

Desired outcome:期望的结果:

print(a)
{"Avv": 33333, "Animal": 22}

You can use this simple one liner你可以使用这个简单的一个班轮

a = {k:v for (k,v) in dict.items() if k.startswith("A")}

You can use a dictionary comprehension:您可以使用字典理解:

a = {key: value for key, value in dict.items() if key.startswith("A")} a = {key:key 的值,dict.items() 中的值 if key.startswith("A")}

Also, I would avoid naming your first dictionary dict .另外,我会避免命名您的第一个字典dict That's a builtin name in Python, so it could mess up code further down the script.这是 Python 中的内置名称,因此它可能会在脚本中进一步混淆代码。 Try something like my_dictionary, or something more descriptive of what it's meant to hold.试试 my_dictionary 之类的东西,或者更能描述它的含义的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 python 中打印字典的键值对 - How do I print the key-value pairs of a dictionary in python 如何将多个列表附加到python字典中的一个键? - How do I append multiple lists to one key in a python dictionary? 如何在python字典中附加键的值? - How do I append the value of a key in a python dictionary? 如何在python中的字典中替换多个键值对? - How to replace multiple key-value pairs in a dictionary in python? 我如何将字典 append 作为现有字典键的另一个值 - How do I append a dictionary as another value to an existing dictionary key 如何在Python3中将字典追加到另一个字典字符串键? - How to append a dictionary to another dictionary string key in Python3? 如何从字典中的字典迭代和 append 键值对并将具有相同键的值存储到列表 python - How to iterate and append key value pairs from a dictionary within a dicionary and storing values with same key into a list python 如何返回一个Python瓶模板,该模板从字典中打印出键/值对? - How do I return a Python bottle template that prints out key-value pairs from a dictionary? 如何在循环中将第二个值附加到字典中的现有键 - How to Append a 2nd value to an existing key in a dictionary in Python in a Loop 如何在Python字典中使用键/值对 - How to use key/value pairs in a Python dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM