Skip to main content
 首页 » 编程设计

python之一个字典的类似字典的字符串列表

2025年05月04日24pengyingh

s=['Closure Type: Button', 'Fit: Regular', 'Neckline: Collar Neck',  
   'Sleeve Length: Long Sleeve', 'Sleeve Style: Cuffed Sleeve'] 

你好,我正在尝试将上面的列表转换成一个字典

键不是我需要更改的所有字符串的常量。

我试过了

data={{k:v} for i in s for k,v in i.split(': ')} 
json.loads(s) 

但是我明白了

ValueError: too many values to unpack (expected 2)

我的预期输出是:

data={'Closure Type':'Button','Fit':'Regular','Neckline':'Collar Neck', 
      'Sleeve Length':'Long Sleeve','Sleeve Style':'Cuffed Sleeve'} 

请您参考如下方法:

关于 data structures page of python documentation : “dict() 构造函数直接从键值对序列构建字典”。

所以这是可行的:

dict(i.split(": ") for i in s)