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:
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}]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With