简体   繁体   中英

extract data from a list of dictionaries python 3

I'm using python3. if I have the following list of dictionaries:

[{'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29}, 
{'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}]

and I want to extract each of stock_symbol, shares_total, and price. and store each of these values in say symbols, shares, prices respectively. how can I do that?

Using List Comprehensions:

mydata = [{'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29}, {'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}]

stock_symbol = [i["stock_symbol"] for i in mydata]
shares_total = [i["shares_total"] for i in mydata]
price = [i["Price"] for i in mydata]

Similarly with the solution from @Stephen Mylabathula, you can create a dictionary with all these lists, like below. You can then call any of these lists with eg result['price']:

result={stock_symbol : [i["stock_symbol"] for i in mydata],
shares_total : [i["shares_total"] for i in mydata],
price : [i["Price"] for i in mydata]}

The easy way is to loop the array only once

mydata = [{'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29}, {'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}]
stock_symbol=[]
shares_total=[]
price=[]

# start loop
for data in mydata:
   stock_symbol.append(data['stock_symbol'])
   shares_total.append(data['shares_total'])
   price.append(data['Price'])

There are many ways to do it.. Some of them

inp = [
    {'stock_symbol': 'ALT', 'shares_total': 1, 'Price': 12.29},
    {'stock_symbol': 'NFLX', 'shares_total': 5, 'Price': 534.5}
]

If codegolfing is not the aim, then the simplest way is to loop the inputs once.

stock_symbols = []
shares_total = []
prices = []
for entry in inp:
    stock_symbols.append(entry['stock_symbol'])
    shares_total.append(entry['shares_total'])
    shares_total.append(entry['Price'])

Same approach but use a dict, so if the keys of the dict change it will be easy to use

from collections import defaultdict
op_dict = defaultdict(list)
fields = ['stock_symbol', 'shares_total', 'Price']

for inp_ in inp:
    for field in fields:
        op_dict[field].append(dict_[field])

op_dict['stock_symbol']
op_dict['shares_total']
op_dict['Price']

Using zip

op_list = list(zip(*(_.values() for _ in inp)))
op_list[0] #stock_symbol
op_list[1] #shares_total
op_list[2] #Price

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM