Python lamba函数转换为字典?

Goo*_*ler 0 python lambda dictionary

我有一个字典表示列表如下:

a = [{'score': 300, 'id': 3}, {'score': 253, 'id': 2}, {'score': 232, 'id': 1}]
Run Code Online (Sandbox Code Playgroud)

我是python的新手,我需要一个python lambda函数,可以通过输出:

dict = [{3:300}, {2:253}, {1:232}]
Run Code Online (Sandbox Code Playgroud)

这样我就可以找到给定值的值

>>> print dict[3]
>>> 300
Run Code Online (Sandbox Code Playgroud)

感谢您对此的帮助.

zha*_*hen 6

  1. 不要dict用作变量名,因为这会影响内置类型名称dict;
  2. {3, 300}不是字典,{3:300}是;

你可以使用dict理解:

In [6]: dic = {d['id']: d['score'] for d in a}

In [7]: dic
Out[7]: {1: 232, 2: 253, 3: 300}
Run Code Online (Sandbox Code Playgroud)

或@jon提到的dict构造函数是为了向后兼容,因为dict-comp仅在py2.7 +上可用:

In [12]: import operator
    ...: dict(map(operator.itemgetter('id', 'score'), a))
Out[12]: {1: 232, 2: 253, 3: 300}
Run Code Online (Sandbox Code Playgroud)