英文:
Filter values from list of dicts by list of values
问题
我有一个类似这样的字典列表:
data = [{'key1':'a', 'key2':'100', '可变的键/值对'}, {'key1':'b', 'key2':'50', '可变的键/值对'}, {'key1':'a', 'key2':'100', '可变的键/值对'}, {'key1':'b', 'key2':'50', '可变的键/值对'}, {'key1':'c', 'key2':'150', '可变的键/值对'},...]
而且我有一个类似这样的过滤器列表(内容和长度可以变化):
filter = ['a', 'b']
我想创建一个新的字典列表,但是要避免重复计数,就像这样:
new_data = [{'key1':'a', 'key2':'100'}, {'key1':'b', 'key2':'50'}]
有什么办法可以实现这个目标吗?
英文:
I have a list of dictionaries like this:
data = [{'key1':'a', 'key2':'100', 'varying key/value pairs'}, {'key1':'b', 'key2':'50', 'varying key/value pairs'}, {'key1':'a', 'key2':'100', 'varying key/value pairs'}, {'key1':'b', 'key2':'50', 'varying key/value pairs'}, {'key1':'c', 'key2':'150', 'varying key/value pairs'},...]
And I have a list of filters like this (which can vary by case in content and length):
filter = ['a', 'b']
And I want to make create new new dictionary, but eliminate double counting like this:
new_data = [{'key1':'a', 'key2':'100'}, {'key1':'b', 'key2':'50'}]
Any ideas how to achieve this?
答案1
得分: 1
你可以先将列表转换为集合,然后再将其转换回列表。请注意,新列表中字典的顺序可能与之前的顺序不同,因为集合的特性是无序的。
unique_keys = {d['key1']: d['key2'] for d in data if d['key1'] in filters}
new_data = [{'key1': k, 'key2': v} for k, v in unique_keys.items()]
英文:
you can first convert the list to a set and then convert it back to list. Note that the order of the dict in new list may not be the same as the order as before, as sets are unordered by nature.
unique_keys = {d['key1']: d['key2'] for d in data if d['key1'] in filters}
new_data = [{'key1': k, 'key2': v} for k, v in unique_keys.items()]
答案2
得分: 0
S = {'a', 'b'}
new_data = list({d['key1']: d for d in data if d['key1'] in S}.values())
输出:
[{'key1': 'a', 'key2': '100'}, {'key1': 'b', 'key2': '50'}]
英文:
What about using a set
to select the valid keys and a temporary dictionary (as a dictionary comprehension) to remove the duplicates?
S = {'a', 'b'}
new_data = list({d['key1']: d for d in data if d['key1'] in S}.values())
Output:
[{'key1': 'a', 'key2': '100'}, {'key1': 'b', 'key2': '50'}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论