Finding all the dicts of max len in a list of dicts

You can find the length of the maximum dictionary in the structure, and then use a list comprehension:

ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
_max = max(map(len, ld))
new_result = dict(i for i in enumerate(ld) if len(i[-1]) == _max)

Output:

{1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5}}

Ajax1234 provided a really good solution. If you want something of a beginner level, here's a solution.

ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
ans = dict()
for value in ld:
     if len(value) in ans:
         ans[len(value)].append(value)
     else:
         ans[len(value)] = list()
         ans[len(value)].append(value)
ans[max(ans)]

Basically, you add everything in a dictionary to get the maximum dictionary size to be the key, and dictionary list to be the value, and then get that maximum size list of dictionaries.


There are a number of ways you could do this in python. Here's one example which illustrates a few different python capabilities:

ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
lengths = list(map(len, ld))  # [1, 2, 2]
max_len = max(lengths)  # 2
index_to_max_length_dictionaries = {
    index: dictionary
    for index, dictionary in enumerate(ld)
    if len(dictionary) == max_len
}
# output: {1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5}}