简体   繁体   中英

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 between?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM