[英]Pythonic way to make a key/value pair a dictionary
I have a situation where I'm getting values returned from MongoDB like this: 我有一种情况,我从MongoDB返回的值如下:
{'value': Decimal('9.99'), 'key': u'price'}
{'value': u'1.1.1', 'key': u'version'}
Now, I came up with a few ways to do this, like (albeit one of my sloppier ones): 现在,我提出了几种方法来做到这一点,比如(虽然我的一个比较粗糙的方法):
y[x['key']] = x['value']
but I just have this nagging suspicion that there's either a single or a small combination of built-in methods that would clean is up. 但我只是怀疑这种唠叨的怀疑是内置方法的单一或小组合可以清理。
In Python 2.7+, you could use a dictionary comprehension: 在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'}
Something like: 就像是:
d = dict((x['key'], x['value']) for x in values)
Assuming these values are in some kind of iterateable. 假设这些值是某种可迭代的。
See the documentation for more information. 有关更多信息,请参阅文档 。
One way could be with operator.itemgetter
: 一种方法可以是
operator.itemgetter
:
>>> from operator import itemgetter
>>> lst = [{'value': 9.99, 'key': 'price'}, {'value': '1.1.1', 'key': 'version'}]
>>>
>>> getter = itemgetter('key','value')
>>> dict(getter(dct) for dct in lst)
{'price': 9.99, 'version': '1.1.1'}
Or using map()
/ imap()
as gnibbler suggested: 或者使用
map()
/ imap()
作为gnibbler建议:
>>> dict(map(getter, lst))
{'price': 9.99, 'version': '1.1.1'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.