我在 python 中有一個字串:-
Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10 10:15:22
我如何將其映射到:-
{'apple':105.2 ,'Goog':101,'TSLA':200,Time:2021:10:10 10:15:22 }
uj5u.com熱心網友回復:
這將引發錯誤。字典值不能有多個由冒號分隔的數值(如Time鍵所示)。我想你的意思是:
dictionary = {'apple': 105.2, 'Goog': 101, 'TSLA': 200, 'Time': '2021:10:10:23'}
您可以使用以下代碼:
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]
注意:這仍會將數字保留為字串文字。
uj5u.com熱心網友回復:
開始:
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]
uj5u.com熱心網友回復:
用逗號分割字串,跳過第一部分。然后通過在第一個冒號上拆分它們在字典建構式中使用這些字串:
s = 'Stock Price,apple:105.2,Goog:101,TSLA:200,Time:2021:10:10:23'
d = dict(kv.split(':',1) for kv in s.split(',')[1:])
print(d)
{'apple': '105.2', 'Goog': '101', 'TSLA': '200', 'Time': '2021:10:10:23'}
您必須執行額外的步驟才能將“時間”值轉換為實際的日期時間物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311497.html
上一篇:對串列中的元素進行分組
下一篇:如何確保串列為空白
