从字典列表中根据值列表筛选数值。

huangapple go评论74阅读模式
英文:

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'}]

huangapple
  • 本文由 发表于 2023年2月27日 02:34:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定