简体   繁体   English

是否可以使用列表推导从dicts的词典创建所有成员dict键的列表?

[英]Can a list of all member-dict keys be created from a dict of dicts using a list comprehension?

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的键将始终是唯一的。

Here's one way to do it: 这是一种方法:

>>> [k for d in foo.values() for k in d]
['key1', 'key2', 'key3', 'key4', 'key5']

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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