[英]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}
. {'b': 2, 'c': 3}
和{'d': 4, 'e': 5}
。
I'm not very knowledgeable in Python but I found that:我对 Python 不是很了解,但我发现:
>>> 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. Ajax1234 提供了一个非常好的解决方案。 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.在 python 中有很多方法可以做到这一点。 Here's one example which illustrates a few different python capabilities:这是一个示例,它说明了几种不同的 Python 功能:
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它只是在完整的输入列表中迭代 1 次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.