1

I have a dictionary in my python program, it looks like this:

cities = {'England'  : ['Manchester'],
          'Germany'  : ['Stuttgart'],
          'France'   : ['Paris', 'Lyonn'],
          'Italy'    : ['Torino']}

Now I want to convert this dictionary in a form like this:

cities = {'England'  : set(['Manchester']),
         'Germany'   : set(['Stuttgart']),
         'France'    : set(['Paris', 'Lyonn']),
         'Italy'     : set(['Torino'])}

Does anyone have any idea?

falco
  • 165
  • 1
  • 4
  • 14

2 Answers2

4

Simple, use a dictionary comprehension:

{key: set(value) for key, value in cities.items()}

This maps each list value to a set object, as a new dicitonary object.

If you are using Python 2, using cities.iteritems() instead will be more efficient.

Demo:

>>> cities = {'England'  : ['Manchester'],
...           'Germany'  : ['Stuttgart'],
...           'France'   : ['Paris', 'Lyonn'],
...           'Italy'    : ['Torino']}
>>> {key: set(value) for key, value in cities.items()}
{'Italy': set(['Torino']), 'Germany': set(['Stuttgart']), 'England': set(['Manchester']), 'France': set(['Paris', 'Lyonn'])}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can use

dict([(k, set(v)) for k,v in cities.items()])
Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • 1
    The `[..]` list comprehension is overkill, you can use a generator expression instead by simply removing the two brackets. Otherwise, that's what you'd use in Python 2.6 or lower, as there you don't yet have a dictionary comprehension syntax. – Martijn Pieters Feb 04 '15 at 11:49
  • I am using python 2.6 :( – Nilesh Feb 04 '15 at 17:02
  • Sure, see [Alternative to dict comprehension prior to Python 2.7](http://stackoverflow.com/q/21069668), use `dict((k, set(v)) for k,v in cities.iteritems())` – Martijn Pieters Feb 04 '15 at 17:03