falco
falco

Reputation: 165

Converting to a set dictionary in Python

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?

Upvotes: 1

Views: 300

Answers (2)

Neel
Neel

Reputation: 21317

You can use

dict([(k, set(v)) for k,v in cities.items()])

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125068

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'])}

Upvotes: 4

Related Questions