![](/img/trans.png)
[英]Python How to convert string with special characters into a dict in python
[英]How to map an special string to a dict in python?
我有一個像這樣的字符串:
a_1 = 'A=1,B=3,C=3'
我想將此字符串映射到dict
,如下所示:
d_1 = {'A':1,'B':2,'C':3}
我應該怎么做? 我在用:
dict(a_1)
但這返回一個錯誤:
ValueError: dictionary update sequence element #0 has length 1; 2 is required.
您可以使用split()
加上理解力來做到這一點:
d_1 = dict(pair.split("=") for pair in a_1.split(","))
強制轉換為int
:
>>> s = 'A=1,B=3,C=3'
>>> dict((k, int(v)) for k, v in [x.split("=") for x in s.split(",")])
{'A': 1, 'C': 3, 'B': 3}
更新:試圖將值強制轉換為int
:
def maybeint(s):
try:
return int(s)
except ValueError:
return s
s = 'A=1,B=3,C=3,D=a'
d = dict((k, maybeint(v)) for k, v in [x.split("=") for x in s.split(",")])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.