转换为 Python 中的集合字典

Converting to a set dictionary in Python

我的 python 程序中有一个字典,它看起来像这样:

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

现在我想把这本字典转换成这样的形式:

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

有人知道吗?

简单,用字典理解:

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

这会将每个列表值映射到一个集合对象,作为一个新的字典对象。

如果您使用的是 Python 2,则使用 cities.iteritems() 会更有效率。

演示:

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

您可以使用

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