Reputation: 47
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?
Upvotes: 0
Views: 79
Reputation: 1902
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
Upvotes: 0
Reputation: 1432
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'])
Upvotes: 0
Reputation: 10624
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]}
Upvotes: 0
Reputation: 398
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]
Upvotes: 6