'What is the fastest way to extract the column values in a list of dictionary?
I have a list of dictionary like this:
[{'open': '38532.5', 'high': '38578', 'low': '38517', 'close': '38578'},
{'open': '38578', 'high': '38588.5', 'low': '38501', 'close': '38573.5'},
{'open': '38573.5', 'high': '38574', 'low': '38552.5', 'close': '38553'}]
Usually, every dictionary has the same keys. What is the fastest way to extract a specific key and output the values as a list? If I set the parameter to be 'open', it will be:
['38532.5', '38578', '38573.5']
I want the fastest way to do it. Many thanks!
Solution 1:[1]
With a list comprehension:
a = [{'open': '38532.5', 'high': '38578', 'low': '38517', 'close': '38578'},
{'open': '38578', 'high': '38588.5', 'low': '38501', 'close': '38573.5'},
{'open': '38573.5', 'high': '38574', 'low': '38552.5', 'close': '38553'}]
[i['open'] for i in a]
Output:
['38532.5', '38578', '38573.5']
Solution 2:[2]
List comprehensions will do this pretty quick.
data = [{'open': '38532.5', 'high': '38578', 'low': '38517', 'close': '38578'},
{'open': '38578', 'high': '38588.5', 'low': '38501', 'close': '38573.5'},
{'open': '38573.5', 'high': '38574', 'low': '38552.5', 'close': '38553'}]
processed = [datum['open'] for datum in data]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nin17 |
| Solution 2 | Jordan Bonecutter |
