Maybe a very common and easy question in here... my purpose is that grouping a dictionary according to its values for example;
D = {"k1":1,"k2":2,"k3":1,"k4":0,"k5":1,"k6":0}
output look like
part1=[0,[k4,k6]] part2=[1,[k1,k3,k5]] part3=[2,[k2]]
Maybe a very common and easy question in here... my purpose is that grouping a dictionary according to its values for example;
D = {"k1":1,"k2":2,"k3":1,"k4":0,"k5":1,"k6":0}
output look like
part1=[0,[k4,k6]] part2=[1,[k1,k3,k5]] part3=[2,[k2]]
def filter_by_value(dictionary, value):
return [value, [i for i in dictionary if dictionary[i] == value]]
And if you want to do it with all the values the dictionary has you can just do:
def group_by_values(dictionary):
#set ensures there are no repeated values
return [filter_by_value(dictionary, i) for i in set(dictionary.values())]
Last but not least, if you want the list to be sorted just add a sorting function after the 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()))]