sasaki085
sasaki085

Reputation: 33

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

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!

Upvotes: 2

Views: 72

Answers (4)

mozway
mozway

Reputation: 260410

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

Upvotes: 4

Afrcvn
Afrcvn

Reputation: 134

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
 

Upvotes: 0

Ammar Bin Aamir
Ammar Bin Aamir

Reputation: 115

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)

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

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

Upvotes: 3

Related Questions