简体   繁体   中英

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

I have a list of dictionaries

ld = [{'a': 1}, {'b': 2, 'c': 3}, {'d': 4, 'e': 5}]

I need to get all the elements with the longest length from my list, ie

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

I'm not very knowledgeable in Python but I found that:

>>> max(ld, key=len)
{'b': 2, 'c': 3}  

And, an even better solution that returns the index of the longest length dictionary:

>>> max(enumerate(ld), key=lambda tup: len(tup[1]))
(1, {'b': 2, 'c': 3})

I would like to use an expression that would return something like

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

and I feel like I'm not far from the solution (or maybe I am) but I just don't know how to get it.

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

Find the maximum length and then use a dictionary comprehension to find the dictionaries with such length

max_l = len(max(ld, key=len))
result = {i: d for i, d in enumerate(ld) if len(d) == max_l}

This is the simplest and more readable approach you can take

Below is another path, a better (but more verbose) approach

max_length = 0
result = dict()

for i, d in enumerate(ld):
    l = len(d)

    if l == max_length:
        result[i] = d
    elif l > max_length:
        max_length = l
        result = {i: d}

This is the most efficient approach. It just iterate 1 time through the full input list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM