Skip to content Skip to sidebar Skip to footer

Split String Value Of A Dictionary

I have this dictionary: { 1: '1 2', 2: '2 3', 3: '2 3', ... } And I want to separate the value of each key to a list of individual elements So I want it to look li

Solution 1:

Using dict comprehension:

>>> 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]}

Reverse:

>>> {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'}

Solution 2:

use the 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()}

Solution 3:

String split will split your values on white space. str.split()

So you just have to iterate key, values of your dict and update the value:

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

Post a Comment for "Split String Value Of A Dictionary"