简体   繁体   中英

How Would I turn a dictionary with values of integers into a dictionary with values of lists in python

I'm Trying to create a program and need help turning a dictionary with string keys and integer values into the same list but with list values. For Example:

dictionary = {"AAPL": 1000, "MSFT": 2000, "TSLA": 1500}
#Somehow turn this dictionary into this:
dictionary = {"AAPL": [1000], "MSFT": [2000], "TSLA": [1500]}

Does anyone know how to do it?

Id then eventually add values to specific key pairs to get something like this:

dictionary = {"AAPL": [1000, 1100], "MSFT": [2000, 2400], "TSLA": [1500, 1450]}

I am using Python btw. Thanks

Use a dictionary comprehension and simply put the value inside a list literal.

dictionary = {key: [value] for key, value in dictionary.items()}
for k,v in dictionary.items():
    dictionary[k]=[v]

desired result:

{'AAPL': [1000], 'MSFT': [2000], 'TSLA': [1500]}

Later:

dictionary['AAPL'].append(1500)

You'll get:

{'AAPL': [1000, 1500], 'MSFT': [2000], 'TSLA': [1500]}

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