字典的字典数组?

Ric*_*ard 6 python mapping dictionary python-2.7 python-3.x

我有一系列字典看起来像这样:

[
  { 'country': 'UK', 'city': 'Manchester' },
  { 'country': 'UK', 'city': 'Liverpool' },
  { 'country': 'France', 'city': 'Paris' } ...
]
Run Code Online (Sandbox Code Playgroud)

我想最终得到这样的字典:

{ 'Liverpool': 'UK', 'Manchester': 'UK', ... }
Run Code Online (Sandbox Code Playgroud)

显然我可以这样做:

 d = {}
 for c in cities:
     d[c['city']] = c['country']
Run Code Online (Sandbox Code Playgroud)

但有什么方法可以用单线图做到吗?

Kas*_*mvd 10

你可以使用dict理解:

>>> li = [
...   { 'country': 'UK', 'city': 'Manchester' },
...   { 'country': 'UK', 'city': 'Liverpool' },
...   { 'country': 'France', 'city': 'Paris' }
... ]

>>> {d['city']: d['country'] for d in li}
{'Paris': 'France', 'Liverpool': 'UK', 'Manchester': 'UK'}
Run Code Online (Sandbox Code Playgroud)

或者我们operator.itemgettermap功能:

>>> dict(map(operator.itemgetter('city','country'),li))
{'Paris': 'France', 'Liverpool': 'UK', 'Manchester': 'UK'}
Run Code Online (Sandbox Code Playgroud)