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