[英]Is there a better way to create a dictionary with key and value from a list of dictionaries dynamically?
input = [
{'key': '1', 'value': 'a'},
{'key': '2', 'value': 'b'},
{'key': '3', 'value': 'c'}
]
{
"1": "a",
"2": "b",
"3": "c"
}
我试过的:
output = {list(entry.values())[0]: list(entry.values())[1] for entry in input}
print(output) #{'1': 'a', '2': 'b', '3': 'c'}
我的问题是有更好的方法来代替每个entry
获取值列表并访问第一个或第二个!
任何建议以更简单的方式进行!
由于entry
是一个 dict,因此使用键访问数据,这就是您应该如何操作 dict
values = [
{'key': '1', 'value': 'a'},
{'key': '2', 'value': 'b'},
{'key': '3', 'value': 'c'}
]
output = {entry['key']: entry['value'] for entry in values}
input
是用于读取用户输入的python内置方法,不要将其用作变量名
最好的方法是:
{x["key"]: x["value"] for x in input}
但不要使用 input 作为变量名 - 它会覆盖内置的 Python 函数输入。
您可以使用operator.itemgetter
从键'key'
和'value'
生成 2 元组。 将生成的序列映射到dict
构造函数进行输出:
from operator import itemgetter
output = dict(map(itemgetter('key', 'value'), input))
这有效:
output = {entry['key'] : entry['value'] for entry in input}
print(output)
但正如其他人所提到的,不要在 python 中使用“输入”作为变量名。 这个术语已经内置在 python 中,覆盖它可能会在以后导致错误和问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.