问题 dict理解中的多个键值对


我试图在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理解可以使用多个键:值对吗?


10851
2018-06-01 19:59


起源

wp_users列表? - amey91
第二种方式适合我。什么类型 wp_users? - RodrigoOlmo
围绕着托架 e[0] 这里没用 - Eric
wp_users是一个元组。 - mdxprograms
当我尝试访问'post_author'时,例如: wp_users_list['post_author'] 就在我得到的时候 "list indices must be integers, not str" - mdxprograms


答案:


字典理解只能产生  每次迭代的键值对。然后诀窍是产生一个额外的循环来分离出对:

{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

12
2017-09-12 21:23





我认为你的问题是第二个版本正在创建一个 名单 字典,而不仅仅是  字典。您正在尝试使用字符串访问列表,这会引发错误:

>>> 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'
>>> 

0
2018-06-02 01:03