按键以最高频率对字典进行排序

时间:2017-09-06 04:26:49

标签: python-3.x sorting

我正在尝试对字典列表进行排序。并且想要返回按频率(最多到最少)键排序的orderedDictionary。

 data = [{'123':'abc'}, {'123':'def'}, {'125':'123'}, {'125':'123243'}, {'125':'12312'} ]

我的方法是获取每个键的频率,然后返回具有适当键值对的字典。 这就是我尝试过的,但这似乎并不是解决这个问题的最灵活方式。有什么建议吗?

由于

freq_dict = {}
    for x_dict in data:
        for key in x_dict:
            if key in freq_dict:
                freq_dict[key] = freq_dict[key] + 1
            else:
                freq_dict[key] = 1
    s = [(k, freq_dict[k]) for k in sorted(freq_dict, key=freq_dict.get, reverse=True)] 
    print(s)

2 个答案:

答案 0 :(得分:2)

这个怎么样:

from collections import Counter

# input data
data = [{'123': 'abc'}, {'123': 'def'}, {'125': '123'}, {'125': '123243'}, {'125': '12312'}]

# count occurrence of first key in each dict in list
# this produces a dictionary with the data's keys
# ('123', '125', etc) as keys and the counts as values
counts = Counter([list(d.keys())[0] for d in data])

# sort by descending frequency of keys
data_sorted = sorted(
    data,
    key=lambda item: counts[list(item.keys())[0]], # function to lookup freq from counts
    reverse=True # descending order
)

print(data_sorted)

这导致:

[{'125': '123'}, {'125': '123243'}, {'125': '12312'}, {'123': 'abc'}, {'123': 'def'}]

答案假设数据列表中的每个字典都是统一长度。

答案 1 :(得分:1)

获取字典键频率的最简单方法可能是use a collections.Counter。这样工作原理如下:

from collections import Counter

freq = Counter(k for d in data for k in d)

现在freq是一个字典,其中每个键都作为键,并且该键出现的次数是该值。使用sorted和可选的key参数将该字典按升序排序到键列表中:

freq_list = sorted(freq, key=freq.get)

使用.reverse()将列表按原样切换为降序:

freq_list.reverse()

最后,使用sorted函数再次创建最终的排序列表,可选的key参数引用index的{​​{1}}方法(关键字为作为参数的字典 - 我们使用lambda来实现这一点:

freq_list

result = sorted(data, key = lambda d: freq_list.index(list(d)[0])) 的{​​{1}}参数的说明:此参数是接受一个参数的任何函数。 key算法采用不知道如何处理的值,并对该值执行sorted函数。该函数的结果决定了排序顺序。

例如,在提供字典的sorted方法时,结果将根据相关字典的自然顺序进行排序,因为key返回一个值从给定的密钥。提供列表的get()方法时,项目排序顺序将与该其他列表中的项目顺序相匹配。