[英]how to sort a list of dictionaries based on how many times a value occours
i have a list of dictionaries and i need to know which name has a given value in the same dictionary for the most times我有一个字典列表,我需要知道哪个名字在同一个字典中有最多的给定值
i need to do this with no imported modules我需要在没有导入模块的情况下执行此操作
[
{"name": name1, "value": value1}
{"name": name2, "value": value1}
{"name": name1, "value": value1}
]
for example here if the given value is value1 i would get name1 as a result because it occours 2 times in the same dictionary as name1例如这里如果给定值是 value1 我会得到 name1 作为结果,因为它在与 name1 相同的字典中出现 2 次
note: value1 could also occour with another name other than name1 so i not only need to know the name it occours with but the name it occours with the most注意:value1 也可能与 name1 以外的其他名称一起出现,所以我不仅需要知道它出现的名称,而且还需要知道它出现次数最多的名称
it is a bit hard to explain i hope someone understands the problem.有点难以解释我希望有人能理解这个问题。
have no idea on how to effectively solve this problem不知道如何有效地解决这个问题
If I understand your request, you are looking for the content of the 'name' key which is repeated the most across the entries where the 'value' key is a particular value.如果我理解您的请求,您正在寻找“名称”键的内容,该内容在“值”键是特定值的条目中重复次数最多。 This function does that without imports by:
这个 function 通过以下方式在没有进口的情况下做到这一点:
def f(data, search):
a = [x['name'] for x in data if x['value'] == search]
return max([(x,a.count(x)) for x in set(a)], key=lambda x: x[1])
Usage:用法:
data = [
{"name": 'name1', "value": 'value1'},
{"name": 'name2', "value": 'value1'},
{"name": 'name1', "value": 'value1'},
{"name": 'name2', "value": 'value2'},
{"name": 'name2', "value": 'value2'},
{"name": 'name1', "value": 'value3'}
]
print(f(data,'value1'))
Here is an alternative and efficient approach using the get()
method:这是使用
get()
方法的另一种有效方法:
given_value = 'value1'
name_counts = {}
for d in list_of_dicts:
if d['value'] == given_value:
name_counts[d['name']] = name_counts.get(d['name'], 0) + 1
most_common_name = max(name_counts, key=name_counts.get)
print(f"Most occurrence is: {most_common_name}. Count: {name_counts[most_common_name]}")
Most occurrence is: name1. Count: 2
You can use an auxillary dictionary to keep track of the number of times the value is associated with a specific name.您可以使用辅助字典来跟踪值与特定名称相关联的次数。
def getNameWithMaxOccur(value):
b = {} # name as key, number of occurrences as value
for d in a:
if d["value"] == value:
if d["name"] not in b:
b[d["name"]] = 1
else:
b[d["name"]] += 1
return max(b, key=b.get) # name with max number of occurrences
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.