python - 在 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)字段的键id
和datetime
。
我这样做如下:
list(map(lambda element: element[0], filter(lambda cel: {'id', 'datetime'}.issubset(set(cel[1]['col'])), MY_ORDERED_DICT.items())))
它似乎工作得很好。它确实返回:
['table2', 'table4', 'table5']
我的问题是我担心有人会看到它并告诉我它太复杂了。
我正在寻找以更优雅的方式做这件事的灵感。
解决方案
不要使用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']
推荐阅读
- python - Python 3.9 - 通过 .csv 交互时出现列表索引超出范围错误,通过添加打印语句伪解决。可能的错误?
- regex - 正则表达式字符串中的括号
- java - ObjectInputStream 的 Mockito 和 PowerMock
- java - 数据库数据升级,按环境进行版本控制
- python - 尽管使用了 .text 方法,但在我的 python selenium 中获取 NoneType
- unit-testing - 如何为python3 unittest中的每个测试方法初始化一个假环境?
- ruby - *ruby*我如何开发一个 Ruby 程序,根据用户的要求打印斐波那契数列的项数和质数
- c++ - 是什么导致命令被信号 11 终止?
- jenkins - 如何将 Jenkins 全局凭证移动到 Job 文件夹
- javascript - 如何生成带有链接的html页面