我正在尝试在这样的 dict 理解中创建多个 key : value 对:
{'ID': (e[0]), 'post_author': (e[1]) for e in wp_users}
我收到 "missing ','"
我也试过这样:
[{'ID': (e[0]), 'post_author': (e[1])} for e in wp_users]
然后我收到 “列表索引必须是整数,而不是 str”
我了解,但不确定纠正此问题的最佳方法以及是否可以使用 dict 理解多个 key : value 对?
最佳答案
字典推导式每次迭代只能产生 一个 键值对。诀窍是产生一个额外的循环来分离这些对:
{k: v for e in wp_users for k, v in zip(('ID', 'post_author'), e)}
这相当于:
result = {}
for e in wp_users:
for k, v in zip(('ID', 'post_author'), e):
result[k] = v
请注意,这只是在您的每个 wp_users
列表中重复两个键,因此您会不断地用新值替换相同的键!在这种情况下,您不妨只取最后一个条目:
result = dict(zip(('ID', 'post_author'), wp_users[-1]))
您没有分享您预期的输出。
如果想法是有一个字典列表,每个字典都有两个键,那么您希望将上述表达式的列表理解应用于每个 wp_users
条目:
result = [dict(zip(('ID', 'post_author'), e)) for e in wp_users]
这会产生与您自己的第二次尝试相同的输出,但现在您有一个 list 字典。您必须使用整数索引来访问其中一个字典对象或使用更多循环。
关于python - dict理解中的多个键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983908/