本文介绍了dict理解中的多个键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在这样的字典理解中创建多个key:value对:

I am trying to create multiple key : value pairs in a dict comprehension like this:

{'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理解是否可能纠正多个键:值对的最佳方法?

Which I understand, but not sure the best way in correcting this and if multiple key : value pairs is possible with dict comprehensions?

推荐答案

字典理解每次迭代只能生成一个键-值对.然后,诀窍是产生一个额外的循环以分离出配对:

A dictionary comprehension can only ever produce one key-value pair per iteration. The trick then is to produce an extra loop to separate out the pairs:

{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

这篇关于dict理解中的多个键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:50