[英]Python: filter list of dictionaries based on multiple key values
I am importing a log file with JSON-like dictionaries and attempting to: 1)only include logs where all three keys are included 2)create a new list of dictionaries that only have these key/values我正在使用类似 JSON 的字典导入日志文件并尝试:1)仅包含包含所有三个键的日志 2)创建仅包含这些键/值的新字典列表
log:日志:
{"pytest_version": "7.1.e", "$report_type": "SessionStart"}
{"label": "test1", "outcome": "passed", "duration":0.0009}
{"label": "test2", "outcome": "passed", "duration":0.00019}
Script:脚本:
with open('log', 'r') as f:
key_list = ['label', 'outcome']
l = [json.loads(log) for log in logs]
l2 = [{k:v for k, v in d.items() if k in key_list} for d in l]
print(l2)
Output Output
[{},
{'label': 'test1', 'outcome': 'passed'},
{'label': 'test2', 'outcome': 'passed'}]
Why is there an empty dictionary in the results?为什么结果中有一个空字典? And how could it be modified to only include results if the key has a value (eg exclude 'outcome':''
)如果键有值(例如排除'outcome':''
),如何修改它以仅包含结果
The first empty dictionary {}
is there because {"pytest_version": "7.1.e", "$report_type": "SessionStart"}
doesn't contain key 'label'
or 'outcome'
.第一个空字典{}
在那里,因为{"pytest_version": "7.1.e", "$report_type": "SessionStart"}
不包含键'label'
或'outcome'
。
One solution might be using all()
to keep only the dictionaries which contains all keys in the key_list
:一种解决方案可能是使用all()
仅保留包含key_list
中所有键的字典:
logs = [
{"pytest_version": "7.1.e", "$report_type": "SessionStart"},
{"label": "test1", "outcome": "passed", "duration": 0.0009},
{"label": "test2", "outcome": "passed", "duration": 0.00019},
]
key_list = ["label", "outcome"]
print(
[{k: d[k] for k in key_list} for d in logs if all(k in d for k in key_list)]
)
Prints:印刷:
[{'label': 'test1', 'outcome': 'passed'}, {'label': 'test2', 'outcome': 'passed'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.