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, i.e.
{'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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With