-1

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}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
A23
  • 1,596
  • 2
  • 15
  • 31

1 Answers1

5

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())
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343