2014-02-27 37 views
-1

有没有在Python的方式为字典。Python的单个语句字典生成

new_list = [x for x in items] 

(列表理解)?像

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

东西,所以我得到

{x: y} 
+0

注:在这种特殊情况下,你可以只是做:'new_dict =字典(items.iteritems ())'。 – iCodez

+0

是的,当然,你是对的 – A23

回答

4

是,通过:

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

它被称为dict comprehension,你需要Python 2.7版或为语法更新。

在Python 2.6和更早的版本,用生成器表达式和dict()调用,喂养它(key, value)元组:

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

嘎,我正在查找文档链接,你打败了我。 :) –

+0

完美!并感谢您的正确任期和参考 – A23

+0

保持与2.6示例向后兼容的好工作。 –