首页 > 解决方案 > 在 Ordered dict 上执行过滤器映射操作的“更简单”的方法

问题描述

我有一个有序的字典如下:

MY_ORDERED_DICT = OrderedDict([
    ('table1', {
        'required': True,
        'col': OrderedDict([
            ('id',                 'aaa'),
            ('registration_date',       'aaa'),
            ('date_of_birth',           'aaa'),
        ])
    }),
    ('table2', {
        'required': True,
        'col': OrderedDict([
            ('product_id',      'aaa'),
            ('id',              'aaa'),
            ('datetime',        'aaa'),
            ('quantity',        'aaa'),
        ])
    }),
    ('table3', {
        'required': False,
        'col': OrderedDict([
            ('product_id',      'aaa'),
            ('brand',           'aaa'),
            ('name',            'aaa'),
        ])
    }),
    ('table4', {
        'required': False,
        'col': OrderedDict([
            ('campaign_id',     'aaa'),
            ('id',         'aaa'),
            ('datetime',  'aaa'),
        ])
    }),
    ('table5', {
        'required': False,
        'col': OrderedDict([
            ('c_id',     'aaa'),
            ('id',         'aaa'),
            ('datetime',  'aaa'),
        ])
    })
])

从这个 OrderedDict 我想提取具有包含字符串的列(也是 OrderedDict)字段的键iddatetime

我这样做如下:

list(map(lambda element: element[0], filter(lambda cel:  {'id', 'datetime'}.issubset(set(cel[1]['col'])), MY_ORDERED_DICT.items())))

它似乎工作得很好。它确实返回:

['table2', 'table4', 'table5']

我的问题是我担心有人会看到它并告诉我它太复杂了。

我正在寻找以更优雅的方式做这件事的灵感。

标签: pythonpython-3.x

解决方案


不要使用map()andfilter()当列表理解会更清晰时:

[
    key for key, value in MY_ORDERED_DICT.items()
    if {"id", "datetime"} <= value["col"].keys()
]

请注意,键字典视图也是一个集合<=,您可以使用or运算符测试字典是否具有最小键集,>=以确定一个是子集还是超集。

上面的代码与您的代码所做的工作相同,因此产生相同的输出:

>>> [
...     key for key, value in MY_ORDERED_DICT.items()
...     if {"id", "datetime"} <= value["col"].keys()
... ]
['table2', 'table4', 'table5']

推荐阅读