拆分字典的字符串值

时间:2013-10-18 03:31:37

标签: python dictionary split

我有这本词典:

{
    1: '1 2',
    2: '2 3',
    3: '2 3',
    ...
}

我想将每个键的值分成单个元素列表 所以我希望它看起来像这样:

{
    1: [1,2],
    2: [2,3],
    ...
}

3 个答案:

答案 0 :(得分:1)

使用dict理解:

>>> d = {
...     1: '1 2',
...     2: '2 3',
...     3: '2 3',
...     4: '4 3 1',
...     5: '3 4',
...     6: '5 4 2 1',
...     7: '4 4',
...     8: '8 3 5 2',
...     9: '5 7',
...     10: '15 11 8 9 6 3 4',
...     11: '6 2',
...     12: '9 5',
...     13: '7 3',
... }
>>> d2 = {key: list(map(int, value.split())) for key, value in d.items()} # `list` can be omitted in Python 2.7
>>> d2
{1: [1, 2], 2: [2, 3], 3: [2, 3], 4: [4, 3, 1], 5: [3, 4], 6: [5, 4, 2, 1], 7: [4, 4], 8: [8, 3, 5, 2], 9: [5, 7], 10: [15, 11, 8, 9, 6, 3, 4], 11: [6, 2], 12: [9, 5], 13: [7, 3]}

反向:

>>> {key: ' '.join(map(str, value)) for key, value in d2.items()}
{1: '1 2', 2: '2 3', 3: '2 3', 4: '4 3 1', 5: '3 4', 6: '5 4 2 1', 7: '4 4', 8: '8 3 5 2', 9: '5 7', 10: '15 11 8 9 6 3 4', 11: '6 2', 12: '9 5', 13: '7 3'}

答案 1 :(得分:0)

使用str.split()

d = { 1: '1 2', 2: '2 3', 3: '3 4' }
wanted = {key: [int(val) for val in value.split()] for key, value in d.iteritems()}

答案 2 :(得分:0)

字符串拆分会将您的值拆分为空白区域。 str.split()

所以你只需要迭代你的dict的键值并更新值:

  for key, value in mydictionary.iteritems():
    mydictionary[key] = value.split()