4

我有这本字典:

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

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

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

3 回答 3

3

使用 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'}
于 2013-10-18T03:35:39.810 回答
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()}
于 2013-10-18T03:35:42.327 回答
0

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

所以你只需要迭代你的字典的键值和值并更新值:

  for key, value in mydictionary.iteritems():
    mydictionary[key] = value.split()
于 2013-10-18T03:36:10.180 回答