嵌套字典理解的执行顺序 [英] Execution order of nested dictionary comprehension

查看:66
本文介绍了嵌套字典理解的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换此列表:

I'm trying to convert this list:

data = [{'A': 123}, {'B': 456}, {'C': 789}]

转到此字典:

{'A': 123, 'B': 456, 'C': 789}

通过词典理解:

{key: value for key, value in dictionary.items() for dictionary in data}

例外:

NameError: name 'dictionary' is not defined

推荐答案

您需要切换迭代逻辑.字典(或 list )理解中的默认迭代顺序从左到右:

You need to switch your iteration logic. Default order of iteration inside dictionary (or list) comprehension goes from left to right:

>>> data = [{'A': 123}, {'B': 456}, {'C': 789}]

>>> {k: v for d in data for k, v in d.items()}
{'A': 123, 'B': 456, 'C': 789}

您可以使用 {} 创建嵌套的字典理解列表理解生成器表达式[] ()分别是我前面提到的从左到右执行顺序的例外.所有这些操作都会创建新对象,并且它们将在自己的作用域内执行.

You can create nested dictionary comprehension, list comprehension or generator expression using {}, [] and () respectively which are the exceptions for the left to right execution order I mentioned earlier. All these operations create new objects, and they execute inside their own scope.

这篇关于嵌套字典理解的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆