按等值对字典进行分组

时间:2017-12-17 20:14:14

标签: python python-3.x dictionary

这里可能是一个非常常见且容易的问题...... 我的目的是根据其值对字典进行分组,例如;

D = {"k1":1,"k2":2,"k3":1,"k4":0,"k5":1,"k6":0}

输出看起来像

part1=[0,[k4,k6]] part2=[1,[k1,k3,k5]] part3=[2,[k2]]

1 个答案:

答案 0 :(得分:1)

def filter_by_value(dictionary, value):
    return [value, [i for i in dictionary if dictionary[i] == value]]

如果你想用字典所拥有的所有值来做,你可以这样做:

def group_by_values(dictionary):
    #set ensures there are no repeated values
    return [filter_by_value(dictionary, i) for i in set(dictionary.values())]

最后但并非最不重要的是,如果您希望对列表进行排序,只需在set:

之后添加一个排序函数
def group_by_values(dictionary):
    #set ensures there are no repeated values
    return [filter_by_value(dictionary, i) for i in sorted(set(dictionary.values()))]