Skip to main content
 首页 » 编程设计

python之在 Python 中将字符串列表转换为字典

2025年05月04日20Free-Thinker

我有一个这样的字符串列表:

l = ['ABC, Apple, 20021015, 20030102', 'CDE, Graps, 20020506, 20030130'] 

我想把这个列表转换成像这样的字典

d = { 'ABC': 'Apple', 'CDE': 'Graps' } 

所以键是字符串中的第一个名字,值是字符串中的第二个名字。

请您参考如下方法:

这适用于 Python 2:

d = {j[0]:j[1] for j in [i.split(', ') for i in l]} 

输出:

{'CDE': 'Graps', 'ABC': 'Apple'}