Say I have a dict of dicts:
说我有一个dicts的词典:
foo = {
'category': {
'key1': 'bar',
'key2': 'bar',
'key3': 'bar',
},
'category2': {
'key4': 'bar',
'key5': 'bar',
},
}
To get a single list of all keys in the member-dicts, I have a function as follows:
要获得member-dicts中所有键的单个列表,我有如下函数:
def _make_list():
baz = list()
for key,val in foo.items():
baz += list(val.keys())
return baz
The generated list looks like: ['key1', 'key2', 'key3', 'key4', 'key5', ]
.
生成的列表如下所示:['key1','key2','key3','key4','key5',]。
This is simple enough, and it works, but I wonder: is there a way to accomplish this with a one-liner list comprehension? The keys of the member dicts will always be unique.
这很简单,并且它可以工作,但我想知道:有没有办法通过单行列表理解来实现这一点?成员dicts的键将始终是唯一的。
2 个解决方案
#1
12
Here's one way to do it:
这是一种方法:
>>> [k for d in foo.values() for k in d]
['key1', 'key2', 'key3', 'key4', 'key5']
#2
3
An approach would be using itertools.chain()
:
一种方法是使用itertools.chain():
import itertools
[k for k in itertools.chain(*(d.keys() for d in foo.values()))]
If what you want is just a one line of code, and not necessarily a list comprehension, you can also try (mentioned by @Duncan):
如果您想要的只是一行代码,而不一定是列表理解,您也可以尝试(由@Duncan提及):
list(itertools.chain(*foo.values()))
Output:
输出:
>>> [k for k in itertools.chain(*(d.keys() for d in foo.values()))]
['key3', 'key2', 'key1', 'key5', 'key4']
>>>
>>> list(itertools.chain(*foo.values()))
['key3', 'key2', 'key1', 'key5', 'key4']
#1
12
Here's one way to do it:
这是一种方法:
>>> [k for d in foo.values() for k in d]
['key1', 'key2', 'key3', 'key4', 'key5']
#2
3
An approach would be using itertools.chain()
:
一种方法是使用itertools.chain():
import itertools
[k for k in itertools.chain(*(d.keys() for d in foo.values()))]
If what you want is just a one line of code, and not necessarily a list comprehension, you can also try (mentioned by @Duncan):
如果您想要的只是一行代码,而不一定是列表理解,您也可以尝试(由@Duncan提及):
list(itertools.chain(*foo.values()))
Output:
输出:
>>> [k for k in itertools.chain(*(d.keys() for d in foo.values()))]
['key3', 'key2', 'key1', 'key5', 'key4']
>>>
>>> list(itertools.chain(*foo.values()))
['key3', 'key2', 'key1', 'key5', 'key4']