Pythonic方法使键/值对成为字典

NFi*_*ano 3 python

我有一种情况,我从MongoDB返回的值如下:

{'value': Decimal('9.99'), 'key': u'price'}
{'value': u'1.1.1', 'key': u'version'}
Run Code Online (Sandbox Code Playgroud)

现在,我提出了几种方法来做到这一点,比如(虽然我的一个比较粗糙的方法):

y[x['key']] = x['value']
Run Code Online (Sandbox Code Playgroud)

但我只是怀疑这种唠叨的怀疑是内置方法的单一或小组合可以清理.

NPE*_*NPE 6

在Python 2.7+中,您可以使用字典理解:

In [2]: l = [{'value': Decimal('9.99'), 'key': u'price'}, {'value': u'1.1.1', 'key': u'version'}]

In [5]: {x['key']: x['value'] for x in l}
Out[5]: {u'price': Decimal('9.99'), u'version': u'1.1.1'}
Run Code Online (Sandbox Code Playgroud)


Fel*_*ing 5

就像是:

d = dict((x['key'], x['value']) for x in values)
Run Code Online (Sandbox Code Playgroud)

假设这些值是某种可迭代的.

有关更多信息,请参阅文档.