How to find the list with most elements in the items of a dict?

Viewed 55

Say that I have

function(Dict[str, List[str]] -> List[str]

how could I return a list that contains the str in the Dict with most elements in the list?

function({'a':['1','2'], 'b':['1'], 'c':['1', '2']})

['a', 'c']

The function should be able to still return the str even if more than one str has the most elements in the list just like the above example. Thank you very much in advance!

4 Answers

Get the max length first, then loop over the elements to filter those that have the max length:

def get_max(d):
    max_len = max(map(len,d.values()))
    return [k for k,v in d.items() if len(v)==max_len]

get_max({'a':['1','2'], 'b':['1'], 'c':['1', '2']})
# ['a', 'c']

One approach:

def fun(d):
    current, res = 0, []
    for k, v in d.items():
        if len(v) > current:
            res = [k]
            current = len(v)
        elif len(v) == current:
            res.append(k)
            current = len(v)
    return res


final = fun({"a": ['1', '2'], "b": ['1'], "c": ['1', '2']})
print(final)

Output

['a', 'c']

Your function will look like this:

def dict_to_max_list(mydict):
    for item in mydict.items():
        mydict[item[0]] = len(item[1])
    all_values = mydict.values()
    max_value = max(all_values)

    # Using list comprehension
    mylist = [x[0] for x in mydict.items() if x[1] == max_value]
    return mylist

The above function accepts a dict. Iterates through your dict and calculate the length of each list in your dict. And then returns list with maximum value using list comprehension.

d1 = {'a':['1','2'], 'b':['1'], 'c':['1', '2']}
list1 = dict_to_max_list(d1)
print(list1)
def function(dict_list: dict):
    #set the max length to 0
    greatest_length = 0
    lists_with_greatest_length = []

    #for each list if the length is greater than greatest_length 
    #we overwrite lists_with_greatest_length with the new list and take its length as the largest.
    for (key, liste) in zip(dictt.keys(), dictt.values()):
        if len(liste) > greatest_length:
           greatest_length = len(liste)
           lists_with_greatest_length = [key]

        elif len(liste) == greatest_length:
           lists_with_greatest_length.append(key)

    return lists_with_greatest_length
 
Related