简体   繁体   English

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

[英]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.

相关问题 在字典列表中查找公用键值对的pythonic方法 - pythonic way to find common key value pair among list of dict 查找与另一个字典中的键、值对匹配的字典的 Pythonic 方法 - Pythonic way to find a dictionary that matches key, value pairs in another dictionary 检查键是否在字典中并且值不为None的大多数pythonic方法 - Most pythonic way of checking if a Key is in a dictionary and Value is not None 在列表中查找具有值的最小字典键的 Pythonic 方法? - Pythonic way to find a minimum dictionary key with value in a list? 用于轮询字典的Pythonic方法 - 一旦存在,就使用密钥的值 - Pythonic way of polling a dictionary - using the key's value once it exists 如何使用字典键,值对来设置类实例属性“pythonic”? - How do I use dictionary key,value pair to set class instance attributes “pythonic”ly? 用Python方式更新字典中的值 - Pythonic way of updating value in dictionary 将列表字典转换为键和值对列表的有效方法 - Efficient way to convert dictionary of list to pair list of key and value 合并具有公共键/值对的两个字典的大多数 Pythonic 方法 - Most Pythonic way to merge two dictionnaries having common key/value pair 弹出键的整洁方式,从字典中值PAIR吗? - Neat way of popping key, value PAIR from dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM