-4

From a dict/list, how to split the list by \n. Eg:

In [1]: d = {'key1': 'value1\n   value2  \n value3\n'}

In [2]: d.values()
Out[2]: ['value1\n   value2  \n value3\n']

Desired output:

['value1', 'value2  ', 'value3']

I looked at existing examples but couldn't find this specific one.

A. Archer
  • 85
  • 2
  • 10
  • 3
    Possible duplicate of [Split string into a list in Python](http://stackoverflow.com/questions/743806/split-string-into-a-list-in-python) –  Aug 17 '16 at 15:34
  • Your desired output shows the string in the values array split by `\n` and then leading (but not trailing) whitespace stripped. Is the stripping of whitespace significant? If so, can you put that in the question? Also, can you give a better example of desired output such as eg when there is more than one entry in the original dict? – davmac Aug 17 '16 at 15:49

3 Answers3

1

Here you go:

d['key1'].split('\n')
fxvdh
  • 147
  • 9
1

You mean you want the values as a flat list? Something like this?

>>> {k: [x.strip() for x in v.splitlines()] for k, v in d.iteritems()}
{'key1': ['value1', 'value2', 'value3']}
Edd Barrett
  • 3,425
  • 2
  • 29
  • 48
  • as BPL points out, remove `iter` from `iteritems` if you use Python3. Why he duplicated my answer, I don't know. – Edd Barrett Aug 17 '16 at 16:04
1

Python 2.x

d = {'key1': 'value1\n   value2  \n value3\n'}
print {k: [x.strip() for x in v.splitlines()] for k, v in d.iteritems()}

Python 3.x

d = {'key1': 'value1\n   value2  \n value3\n'}
print({k: [x.strip() for x in v.splitlines()] for k, v in d.items()})
BPL
  • 9,632
  • 9
  • 59
  • 117