首页 > 解决方案 > 在字典列表中查找最常出现的字典的最佳方法

问题描述

我有一个字典列表,其中每个字典都有键“形状”和“颜色”。例如:

info = [
    {'shape': 'pentagon', 'colour': 'red'},
    {'shape': 'rectangle', 'colour': 'white'},
    # etc etc
]

我需要找到最常见的形状/颜色组合。我决定通过在列表中查找最常出现的字典来做到这一点。我已经将我的方法缩减为:

frequency = defaultdict(int)

for i in info:
    hashed = json.dumps(i) # Get dictionary, turn into string to store as key in frequency dict
    frequency[hashed] += 1

most_common = max(frequency, key = frequency.get) # Get most common key and unhash it back into dict
print(json.loads(most_common))

我对 python 有点陌生,我总是最终发现一些 1-2 行函数最终会做我想做的事情。我想知道在这种情况下是否存在更快的方法?也许这最终可以帮助另一个初学者,因为经过多年的谷歌搜索,我找不到任何东西。

标签: pythonjsondictionary

解决方案


如果列表中的项目具有一致的键,则更好的选择是使用 anamedtuple代替 adict例如:

from collections import namedtuple

# Define the named tuple
MyItem = namedtuple("MyItem", "shape colour")

# Create your list of data
info = [
    MyItem('pentagon', 'red'),
    MyItem('rectangle', 'white'),
    # etc etc
]

这提供了许多好处:

# To instantiate
item = MyItem("pentagon", "red")

# or using keyword arguments
item = MyItem(shape="pentagon", colour="red")

# or from your existing dict
item = MyItem(**{'shape': 'pentagon', 'colour': 'red'})

# Accessors
print(item.shape)
print(item.colour)

# Decomposition
shape, colour = item

然而,回到计数匹配项的问题,因为 anamedtuple是可散列collections.Counter的,所以计数代码变为:

from collections import Counter

frequency = Counter(info)

# Get the items in the order of most common
frequency.most_common()

享受!


推荐阅读