在一个字典列表中找到所有最大长度的字典

7

我有一个字典列表

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

我需要从我的列表中获取所有长度最长的元素,即{'b': 2, 'c': 3}{'d': 4, 'e': 5}。我对Python不是很了解,但我发现:
>>> max(ld, key=len)
{'b': 2, 'c': 3}  

还有一种更好的解决方案,它返回最长长度字典的索引:

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

我想使用一个表达式,返回类似以下内容:

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

我感觉离解决方案不远了(或许我错了),但我不知道该如何得到它。

4个回答

8
您可以在该结构中找到最大字典的长度,然后使用列表推导式:
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)

输出:

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

3

Ajax1234 提供了一个非常好的解决方案。如果你想要一个初级水平的解决方案,这里有一个。

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

基本上,您需要将字典中的所有内容相加,以使最大字典大小成为键,字典列表成为值,然后获取具有该最大大小的字典列表。


2

找到最大长度,然后使用字典推导式来找到具有这种长度的字典

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

这是您可以采取的最简单且易读的方法。
下面是另一种路径,一种更好(但更冗长)的方法。
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}

这是最高效的方法。它只需要一次遍历完整的输入列表。

非常感谢您的详细回复! - Ricardo Jesus
没问题,兄弟!虽然把我的答案标记为正确的会很好笑。LOL - JoshuaCS

2

在Python中,有许多方法可以实现这一点。下面是一个示例,它演示了几种不同的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}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接