简体   繁体   中英

Pythonic way to make a key/value pair a dictionary

I have a situation where I'm getting values returned from MongoDB like this:

{'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:

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 :

>>> 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:

>>> dict(map(getter, lst))
{'price': 9.99, 'version': '1.1.1'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM