Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting dictionary items embedded in a list

Let's say I have the following list of dict

t = [{'a': 1.0, 'b': 2.0},
     {'a': 3.0, 'b': 4.0},
     {'a': 5.0, 'b': 6.0},
     {'a': 7.0, 'b': 9.0},
     {'a': 9.0, 'b': 0.0}]

Is there an efficient way to extract all the values contained in the dictionaries with a dictionary key value of a?

So far I have come up with the following solution

x = []
for j in t:
    x.append(j['a'])

However, I don't like to loop over items, and was looking at a nicer way to achieve this goal.

like image 593
Eric B Avatar asked Sep 27 '17 12:09

Eric B


People also ask

How to extract the dictionary values as a list in Python?

Now, let’s use a list () function to extract the dictionary values as a list: As you can see, the dictionary values were extracted as a list: Now, let’s extract the dictionary values as a list using a list comprehension: Finally, you may use a For Loop to extract the values as a list:

How do you extract data from a list in Python?

The first step is to determine the data type and the second step is to apply the extraction method. If the datatype is list, then use the index operator with square brackets. However, if the datatype is a dictionary, use the dictionary key with curly brackets.

How is a dictionary represented in Python?

In Python, a dictionary is represented in the form of key-value pairs. List of dictionary means multiple dictionaries are enclosed within square brackets.

What does the Dictionary mean in the data type?

The dictionary means that the data can be extracted using a key. In our data, the key used to extract the value is currencies. The currencies key is used in step 9. Take note, the data type changed from <class 'list'> in step 5 to <class 'dict'> in step 8.


1 Answers

You can use list comprehension:

t = [{'a': 1.0, 'b': 2.0},
 {'a': 3.0, 'b': 4.0},
 {'a': 5.0, 'b': 6.0},
 {'a': 7.0, 'b': 9.0},
 {'a': 9.0, 'b': 0.0}]
new_list = [i["a"] for i in t]

Output:

[1.0, 3.0, 5.0, 7.0, 9.0]

Since this solution uses a for-loop, you can use map instead:

x = list(map(lambda x: x["a"], t))

Output:

[1.0, 3.0, 5.0, 7.0, 9.0]

Performance-wise, you prefer to use list-comprehension solution rather the map one.

>>> timeit('new_list = [i["a"] for i in t]', setup='from __main__ import t', number=10000000)
4.318223718035199

>>> timeit('x = list(map(lambda x: x["a"], t))', setup='from __main__ import t', number=10000000)
16.243124993163093


def temp(p):
    return p['a']

>>> timeit('x = list(map(temp, t))', setup='from __main__ import t, temp', number=10000000)
16.048683850689343

There is a slightly difference when using a lambda or a regular function; however, the comprehension execution takes 1/4 of the time.

like image 147
Ajax1234 Avatar answered Sep 21 '22 23:09

Ajax1234