1

I have the following code:

lstcurrencies = ['btc', 'eth', 'usdt']
dict_lstlegacy_symbols = dict.fromkeys(lstcurrencies, []) # creates {'btc': [], 'eth': [], 'usdt': []}

for currency in lstcurrencies:
    print(currency)
    dict_lstlegacy_symbols[currency].append(1)

This creates the three lists:

dict_lstlegacy_symbols['btc']: [1, 1, 1]
dict_lstlegacy_symbols['eth']: [1, 1, 1]
dict_lstlegacy_symbols['usdt']: [1, 1, 1]

What I would actually like to get is:

dict_lstlegacy_symbols['btc']: [1]
dict_lstlegacy_symbols['eth']: [1]
dict_lstlegacy_symbols['usdt']: [1]

I don't understand why it adds the 1 three times instead of only one time. How can I obtain my desired result?

Johannes Walter
  • 1,069
  • 2
  • 10
  • 25

1 Answers1

0

Use defualt dict instead.

from collections import defaultdict

lstcurrencies = ['btc', 'eth', 'usdt']
dict_lstlegacy_symbols =defaultdict(list) 

for currency in lstcurrencies:
    print(currency)
    dict_lstlegacy_symbols[currency].append(1)

print(dict_lstlegacy_symbols)
pjk
  • 547
  • 3
  • 14