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

时间:2015-07-15 03:25:58

标签: python dictionary

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

我试图遍历列表,然后是字符串,但最终迭代1,1,1而不是111作为完整数字。

2 个答案:

答案 0 :(得分:3)

使用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"']}

答案 1 :(得分:1)

或许这样的事情:

strings = ['111,"A","yes"','112,"B","no"','113,C,"maybe"']

# now get rid of the superfluous double quotes with str.replace
# and str.split on the commas to make a list of lists
strings = [s.replace('"', '').split(',') for s in strings]

>>> print strings
[['111', 'A', 'yes'], ['112', 'B', 'no'], ['113', 'C', 'maybe']]

# make the dict with a dict comprehension
d = {int(s[0]):(s[1], s[2]) for s in strings}

>>> print d
{111: ('A', 'yes'), 112: ('B', 'no'), 113: ('C', 'maybe')}

相关链接:

str.split()

str.replace()

相关问题