简体   繁体   中英

Convert dictionary values to dictionary key-value pairs

I have a list of dictionary items as follows:

[{'answer_type': 'Yes', 'answer__count': 5}, {'answer_type': 'No', 
'answer__count': 3}, {'answer_type': 'Maybe', 'answer__count': 2}]

I would like to convert it to the following form:

[{'Yes': 5}, {'No': 3}, {'Maybe': 2}]

I know that I could loop through the dictionary, pull out the items I want and create a new dictionary, but I wanted to know if there is a more elegant way. What is the most efficient way to do this conversion? Thank you.

Let's say that your list of dictionaries is called data .

Then you can convert it with the following code:

newdata = [{dic['answer_type']: dic['answer__count']} for dic in data]

If you don't understand this code well, take a look at Python comprehensions

Assuming your data is stored in d , there are several ways to do this:

List Comprehension

For every iterable you can use a list comprehension , so iterate over the items with [it for it in iterable] (you can use list comprehensions in dictionaries, too).

In [6]: [{dic['answer_type']: dic['answer__count']} for dic in d]
Out[6]: [{'Yes': 5}, {'No': 3}, {'Maybe': 2}]

Functional Approach

If you are more the functional programming guy, consider using a map , which applies a function to each element of an iterable (this is my preferred approach, if I have to do this again and again with a list, I only have to define the function once then):

In [2]: map(lambda dic: {dic['answer_type']: dic['answer__count']}, d)
Out[2]: [{'Yes': 5}, {'No': 3}, {'Maybe': 2}]

For some people this is not as good to read as list comprehensions, for some it's better, depends on personal feelings. This will work with python2, in py3 it gives you an iterator, so you have to use list around the map to get the list.

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