有没有办法在Python中做
new_list = [x for x in items]
(列表理解)的字典?类似的东西
new_dict = [x=>y for x, y in items.iteritems()]
这样我就得到了
{x: y}
是的
,通过使用:
{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())