我试图在dict理解中创建多个键:值对,如下所示:
{'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]
然后我收到了 "list indices must be integers, not str"
我理解,但不确定纠正这个的最佳方法,如果dict理解可以使用多个键:值对吗?
字典理解只能产生 一 每次迭代的键值对。然后诀窍是产生一个额外的循环来分离出对:
{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
我认为你的问题是第二个版本正在创建一个 名单 字典,而不仅仅是 一 字典。您正在尝试使用字符串访问列表,这会引发错误:
>>> obj = [{'data1': 67, 'data2': 78}]
>>> obj[0]['data1']
67
>>> obj['data1']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>>
相反,只需访问第二个版本为`wp_list [0] ['post_author'],它应该工作正常:
>>> wp_users = ('Bob', 'Joe', 'Sally')
>>> wp_list = [{'ID': (e[0]), 'post_author': (e[1])} for e in wp_users]
>>> wp_list[0]['post_author']
'o'
>>> wp_list[1]['post_author']
'o'
>>> wp_list[2]['post_author']
'a'
>>>