Python single statement dictionary generator

Python语句字典生成器

Tags: python
标签: python

问题 (Question)

Is there a way in Python to do

new_list = [x for x in items]

(list comprehension) for a dictionary? Something like

new_dict = [x=>y for x, y in items.iteritems()]

so that I get

{x: y}

有Python的方式去做

new_list = [x for x in items]

(列表)为一本字典吗?像

new_dict = [x=>y for x, y in items.iteritems()]

使我得到

{x: y}

最佳答案 (Best Answer)

Yes, by using:

{x: y for x, y in items.iteritems()}

It's called a dict comprehension, and you need Python 2.7 or newer for that syntax.

In Python 2.6 and earlier, use a generator expression and the dict() callable, feeding it (key, value) tuples:

dict((x, y) for x, y in items.iteritems())

是的,通过使用:

{x: y for x, y in items.iteritems()}

它叫的理解,你需要Python 2.7或更新的,语法。

在Python 2.6和更早的版本中,使用一个发电机的表达和dict()可赎回,喂它(key, value)元组:

dict((x, y) for x, y in items.iteritems())

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/22081754