Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary
And have a big blob of values, with a space in be开发者_如何学Gotween?
Edit: What if I have nested dictionaries? The current solutions work if my values are all strings. But what if my values are nested dictionaries?
Assuming the values are already strings:
>>> d = { 1 : 'foo', 2 : 'bar' }
>>> ' '.join(d.values())
'foo bar'
If not, you can try to convert them to strings using for example str
:
>>> d = { 1 : 2, 3: 4 }
>>> ' '.join(str(v) for v in d.values())
'2 4'
>>> a = {1: 'hello', 2: 'world'}
>>> a.values()
['hello', 'world']
>>> ' '.join(a.values())
'hello world'
if you want the values from a dictionary that contains dictionaries as values, try something like this:
In [1]: from itertools import chain
In [2]: d = {'A': {1: 'pants', 2: 'trowsers'}, 'B': {'1': 'spam', '2': 'eggs'}}
In [3]: values = ' '.join(chain.from_iterable(dic.itervalues() for dic in d.itervalues()))
In [4]: values
Out[4]: 'pants trowsers spam eggs'
精彩评论