[英]How to extract values from list of dictionary that match the keys in another list
I have a list of keys: l_keys = ['a', 'c', 'd']
我有一个键列表:
l_keys = ['a', 'c', 'd']
And I have a list of dictionary: l_dict = [{'a': 1, 'b': 2, 'c': 3}, {'a':4, 'd':5}]
我有一个字典列表:
l_dict = [{'a': 1, 'b': 2, 'c': 3}, {'a':4, 'd':5}]
The result I want to get is: [{'a': 1, 'c': 3}, {'a': 4, 'd': 5}]
我想要得到的结果是:
[{'a': 1, 'c': 3}, {'a': 4, 'd': 5}]
. .
I can achieve this result in the following way我可以通过以下方式实现此结果
[{k: d[key] for k in l_keys if k in l_dict} for d in l_dict]
. .
Explain: I actually go through every object in l_dict and then I go through every key in l_keys and check if that key is in the current object and if so I retrieve it and its value说明:我实际上遍历 l_dict 中的每个对象,然后遍历 l_keys 中的每个键并检查该键是否在当前对象中,如果是,则检索它及其值
My question is if there is a better, professional and faster way in terms of time complexity to do that.我的问题是,在时间复杂度方面是否有更好、专业和更快的方法来做到这一点。
Firstly, your list comprehension should be: [{k: d[k] for k in l_keys if k in d} for d in l_dict]
首先,您的列表理解应该是:
[{k: d[k] for k in l_keys if k in d} for d in l_dict]
If you know that len(l_keys)
will usually be smaller than the dict
s in l_dict
, your way is the most efficient.如果您知道
len(l_keys)
通常会小于l_dict
中的dict
,那么您的方式是最有效的。 Otherwise, it would be better to check whether each key in the dict
is in l_keys
: [{k: d[k] for k in d if k in l_keys} for d in l_dict]
l_set = set(l_keys)
: [{k: d[k] for k in d if k in l_set} for d in l_dict]
否则,最好检查
dict
中的每个键是否在l_keys
中: [{k: d[k] for k in d if k in l_keys} for d in l_dict]
l_set = set(l_keys)
: [{k: d[k] for k in d if k in l_set} for d in l_dict]
This page might be helpful when it comes to time complexity: https://wiki.python.org/moin/TimeComplexity#dict当涉及到时间复杂度时,此页面可能会有所帮助: https ://wiki.python.org/moin/TimeComplexity#dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.