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}
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}
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())