1

I am trying to turn a nested list:

#stock[symbol,price,amount,side]

stocks = [["AAPL",10,5,0],["AAPL",15,2,1],["AAPL",25,1,1],["AAPL",30,4,0],
          ["TSLA",10,5,0],["TSLA",15,2,1],["TSLA",25,1,1],["TSLA",30,4,0]]

into a dictionary like:

#res = {"symbol":{price:total_amount,price:total_amount}

res = {"AAPL":{10:5,15:2,25:1,30:4},"TSLA":{10:5,15:2,25:1,30:4}}

The subdict is calculated by:

subdict ={}

for s,p,a,side in stocks:
     subdict[p] = subdict.get(p,0)+a

The share returns total_share.e.g. if stocks = [["AAPL",10,3,0],["AAPL",10,3,0]] should return {"AAPL":{10:6}}

3
  • 1
    first of You shouldn't unpack values with same variable names as You do here for s, p, a, s ... as You can then s repeats twice, also does unpacking like that even work? Commented Jul 18, 2021 at 20:09
  • The last element into nested list will be ignored? by exemple: ["AAPL",10,5,0] the zero will be ignored? Commented Jul 18, 2021 at 20:13
  • @iL Two tips: 1st pay more attention to the formatting of the text of your question, where it is code format as code. 2nd Describe better what you need in the text, try to verbalize more than and use input and outputs as examples not as the only way of understanding. So you will have your answers faster in the next questions and it helps other people who have the same problems. Commented Jul 19, 2021 at 12:16

4 Answers 4

2
from collections import defaultdict

res = defaultdict(dict)

for stock in stocks:
    res[stock[0]][stock[1]] = stock[2]

I use defaultdict so I do not need to check for the dict key before assigning.

Output:

{'AAPL': {10: 5, 15: 2, 25: 1, 30: 4}, 'TSLA': {10: 5, 15: 2, 25: 1, 30: 4}}
Sign up to request clarification or add additional context in comments.

Comments

1

Updated as your comment

#Create result dict
res={}
for list in stocks:
    key = list[0]
    #Verify if the key are in the dict
    if key not in res :
        res[key]= {}
    #Verify if the 'sub-key' are in the nested-dict
    if list[1] not in res[key] :
        #if dont, initalizes
        res[key][list[1]] = list[2]
    else:
        #Else sum 
        res[key][list[1]] += list[2]

Looking at your data, I'm assuming you want a dictionary with the keys being the first item in each list and the contents a nested dictionary where the keys are the second value of the list and the contents the third value (the fourth and last value will be ignored).

3 Comments

Thanks! I also want to calculate my share as a sum. for example if stocks = [["AAPL",10,3,0],["AAPL",10,3,0]] should return {"AAPL"{10:6}}
@iL Updated as your comment. Dont forget to upvote to all aswer you think is helpfull and accept one of these as solution.
Thanks! I need 15 reputation to cast a vote. I will come back and upvote
1

You can use itertools.groupby to collect each sublist sharing the same symbol into a separate iterator.

from itertools import groupby
from operator import itemgetter

f = itemgetter(0)

res = {symbol: set(f'{v[1]}:{v[2]}' for v in itr)
         for symbol, itr in groupby(sorted(stocks, key=f), f)}

Comments

1

I would consider a defaultdict for this. It will allow you to make the data structure you want in a single pass with good readability.

from collections import defaultdict

stocks = [["AAPL",10,5,0],["AAPL",15,2,1],["AAPL",25,1,1],["AAPL",30,4,0],
          ["TSLA",10,5,0],["TSLA",15,2,1],["TSLA",25,1,1],["TSLA",30,4,0]]

res = defaultdict(dict)

for symbol, k, v, *rest in stocks:
    res[symbol][k] = v

Resulting in

defaultdict(dict,
        {'AAPL': {10: 5, 15: 2, 25: 1, 30: 4},
         'TSLA': {10: 5, 15: 2, 25: 1, 30: 4}})

A defaultdict will operate just like a dict for accessing elements. You can always convert it to a plain dict by passing it to dict()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.