简体   繁体   中英

How to convert list to nested dict?

I am trying to create a nested dicts based the lists bellow.

assets = ["GOOG", "AMZN"]

variables=['LastTradePrice','Spread','QTD']

c = ['0']

I tried the code bellow, but it is missing some information and resulting on a short dict, with only one asset and one variable, I expected 2 assets as 'main keys' and 3 variables as 'sub keys', each 'sub key' followed by 0 as value.

Tried this code:

dct = {x: {str(y): str(z)} for x, y, z in zip(assets,variables,c)}

Result I got:

{'GOOG':{'LastTradePrice':'0'}}

Expected Result:

{'GOOG':{'LastTradePrice': '0','Spread':'0','QTD':'0'}, 'AMZN': {'LastTradePrice':'0','Spread':'0','QTD':'0'}}

Try this

res = {x: dict(zip(variables, c * len(variables))) for x in assets}
print(res)

Output:

{'GOOG': {'LastTradePrice': '0', 'Spread': '0', 'QTD': '0'}, 'AMZN': {'LastTradePrice': '0', 'Spread': '0', 'QTD': '0'}}

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