Home > Back-end >  How to map a String as a dict in python?
How to map a String as a dict in python?

Time:10-11

I have a string in python:-

Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23

How do I map it to:-

{'apple':105.2  ,'Goog':101,'TSLA':200,Time:2021:10:10:23 } 

CodePudding user response:

This will throw an error. A dictionary value can't have multiple numerical values separated by a colon (as shown with the Time key). I think you meant the following:

dictionary = {'apple': 105.2, 'Goog': 101, 'TSLA': 200, 'Time': '2021:10:10:23'}

You can use the following code:

dictionary = {}

string = 'Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23'

# Split the string by commas and store the items in a list
enter code herestring_items = string.split(",") # ['Stock Price', 'apple:105.2', 'Goog:101', 'TSLA:200', 'Time:2021:10:10:23']
     
# Remove the first item (i.e., "Stock Price")
string_items.pop(0)

for item in string_item:
    dictionary[item.split(":", 1)[0]] = item.split(":", 1)[1]

Note: This will still keep the numbers as a string literal.

CodePudding user response:

Here goes:

str = "Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23"

s = str.split(',')[1:]
stocks = {}
for tickr in s:
    new_dict = tickr.split(':')
    stocks[new_dict[0]] = new_dict[1]
  • Related