Home > Software design >  Python loop through list add to dictionary
Python loop through list add to dictionary

Time:06-05

['TSLA220610C00200000', '2022-06-02 1:41PM EDT', '200.00', '580.56', '502.45', '504.35', '0.00', '-', '1', '3', '431.84%', 'TSLA220610C00350000', '2022-06-03 2:29PM EDT', '350.00', '358.80', '352.60', '354.50', '-65.17', '-15.37%', '3', '3', '50.00%']


calls = {"Contract Name":"['TSLA220610C00200000','TSLA220610C00350000']",
        "Last Trade Date":"['2022-06-02 1:41PM EDT','2022-06-03 2:29PM EDT']",
        "Strike":"['200.00','300.00']",
        "Last Price":"['580.56','358.80']",
        "Bid":"['502.45','352.60']",
        "Ask":"['504.35','354.50']",
        "Change":"['0.00','-65.17']",
        "% Change":"['-','-15.37%']",
        "Volume":"['1','3']",
        "Open Interest":"['3','3']",
        "Implied Volatility":"['431.84%','50.00%']"}

I'm trying to loop over this list and add it to a dictionary like the above, is this possible?

CodePudding user response:

If lst is your list from the question you can try:

calls = {
    "Contract Name": [],
    "Last Trade Date": [],
    "Strike": [],
    "Last Price": [],
    "Bid": [],
    "Ask": [],
    "Change": [],
    "% Change": [],
    "Volume": [],
    "Open Interest": [],
    "Implied Volatility": [],
}
for i in range(0, len(lst), len(calls)):
    for v, l in zip(lst[i : i   len(calls)], calls.values()):
        l.append(v)

print(calls)

Prints:

{
    "Contract Name": ["TSLA220610C00200000", "TSLA220610C00350000"],
    "Last Trade Date": ["2022-06-02 1:41PM EDT", "2022-06-03 2:29PM EDT"],
    "Strike": ["200.00", "350.00"],
    "Last Price": ["580.56", "358.80"],
    "Bid": ["502.45", "352.60"],
    "Ask": ["504.35", "354.50"],
    "Change": ["0.00", "-65.17"],
    "% Change": ["-", "-15.37%"],
    "Volume": ["1", "3"],
    "Open Interest": ["3", "3"],
    "Implied Volatility": ["431.84%", "50.00%"],
}
  • Related