Home > Software design >  What is the fastest way to extract the column values in a list of dictionary?
What is the fastest way to extract the column values in a list of dictionary?

Time:05-02

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!

CodePudding user response:

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']

CodePudding user response:

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]
  • Related