python - 从列表中的字符串创建字典?

标签 python dictionary

我有一个列表 ['111,"A","yes"','112,"B","no"','113,C,"maybe"'] 我希望输出为 {111:('A',"yes"),112:('B',"no"),113:('C',"maybe")]}

我尝试遍历列表,然后遍历字符串,但最终遍历了 1,1,1 而不是 111 作为一个完整数字。

最佳答案

使用str.split() :

In [1]: lst = ['111,"A","yes"','112,"B","no"','113,C,"maybe"']

In [2]: dict((int(s[0]), s[1].split(',')) for s in (grp.split(',', 1)
                                          for grp in lst))
Out[2]: {111: ['"A"', '"yes"'],
         112: ['"B"', '"no"'],
         113: ['C', '"maybe"']}

关于python - 从列表中的字符串创建字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420953/

相关文章:

c# - 将 Dictionary<int, List<string>> 分配给空的新声明字典

Python 抽象 setter 和 getter

python - 在 tkinter 按钮中显示图像;垃圾收集/切换框架问题?

python - 使用 Python 在另一个列表中搜索列表的值

c# - 从Dictionary的值中获取名称,以逗号分隔的值字符串

c# - 使用枚举和 |作为字典键

python - 在 python 中抑制 shell 命令的详细输出

python - 如何让 VirtualEnv TensorFlow 在 PyCharm 中工作?

python - 为什么我不能在不可散列实例的明显可散列方法上调用 hash()?

python-3.x - 如何从复杂字典中提取嵌套数据并从中提取嵌套数据以构建新字典?