开发者

Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary

开发者 https://www.devze.com 2022-12-24 18:58 出处:网络
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 nes

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'
0

精彩评论

暂无评论...
验证码 换一张
取 消