按字典值对字典中的每个字典进行排序-Python

时间:2020-05-19 19:44:01

标签: python pandas list dictionary

我正在尝试使用由成堆的单词创建的单词列表来为一系列调查答复创建标签。

每个单词列表是一个字典,是对应于其所在簇的行的一部分。这些属性是PANDAS数据帧的一部分。其他属性将稍后添加到数据框中,因此我需要保留行。

我想按字典中每个单词的计数以降序对每个字典进行排序。单词是键,计数是值。

此数据框包括:

2列数据:df [['cluster#','dictionary']]

集群#=整数

dictionary = {word0:count0,word1:count1,...,wordx:countx}

对于每个群集编号,我希望相应的字典按计数降序排列。 (每个字典都有唯一数量的元素,由元素簇中的唯一单词的数量定义。但这没关系)

如何使用Python执行此操作?我将使用单词列表作为群集的描述性标签。

1 个答案:

答案 0 :(得分:0)

我认为这就是您要尝试做的事情:

# First define a function that reverse-sorts a dictionary by values
def sort_dict(d):
    return {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}

# Apply that function to the 'dictionary' column of your dataframe
df['dictionary'] = df['dictionary'].apply(sort_dict)