Unexpected output when looping through subdictionaries in Python

I have a nested dictionary, where I have tickers to identifiy certain assets in my dictionary and then for each of these assets I would like to store characteristics in a subdictionary for the asset, creating them in a simple loop like the below:

ticker = ["a","bb","ccc"]
ticker_dict = dict.fromkeys(ticker, {"Var":[]})
for key in ticker_dict:
    ticker_dict[key]["Var"] = len(key)

From the above output I would expect, that for each ticker/asset it saves the “Var” variable as the length of its name, meaning the following:

{"a":{"Var":1},
 "bb":{"Var":2},
 "ccc":{"Var":3}}

But, in my view rather weirdly, the result is this

{"a":{"Var":3},
 "bb":{"Var":3},
 "ccc":{"Var":3}}

To provide further context, the real process is that I have four assets, for which I would like to store dataframes in their subdictionaries as this makes it easy for me to access them later in loops etc. Somehow though, the data from the last asset is simply copied over all assets, eventhogh I explicitly loop through different keys.

What’s going on?

PS: I’m not sure how to explain the problem without the sample code, so I might have missed a similar entry on this site. If so, any hints to it would be appreciated as well of course.

Answer

In your code, {"Var":[]} is only evaluated once, causing there to be only 1 inner dictionary shared by all keys. Instead, you can use a dictionary comprehension:

ticker_dict = {key:{"Var":[]} for key in ticker}

and it will work as expected.