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 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

it is a bit hard to explain i hope someone understands the problem.

have no idea on how to effectively solve this problem


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
                b[d["name"]] += 1
    return max(b, key=b.get) # name with max number of occurrences
Answered By: adamius

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:

  1. filtered to the items which match your ‘value’ value
  2. counting the occurrences of each ‘name’ value
  3. returning the name with the largest count
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])


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

Answered By: ricardkelly

Here is an alternative and efficient approach using the get() method:

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
Answered By: Jamiu S.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.