Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary values to dictionary key-value pairs

Tags:

python

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.

like image 489
henrich Avatar asked Feb 24 '18 13:02

henrich


Video Answer


2 Answers

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

like image 54
nyr1o Avatar answered Nov 08 '22 18:11

nyr1o


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.

like image 39
Nico Albers Avatar answered Nov 08 '22 18:11

Nico Albers