Home > front end >  Sort a Dict by values
Sort a Dict by values

Time:12-17

I have a question: in Python

I have a Dict given

W = {'Cat': 2, 'Mice': 2, 'Dog': 5, 'Duck': 2, 'Hamster': 5}

and now I want to sort it, that the new Dict looks like that:

new_Dict = {2 : ['Cat','Mice', 'Duck'], 5 : ['Dog','Hamster']}

I already found some solutions in the Internet, but I am pretty new to programming, so I don't really understand them. So for we had "for ... in range()", "while..." and "def ()" in school (and the absolute basic stuff ^^)

Thank you in advance :)

CodePudding user response:

Simple solution using for loop:

W = {'Cat': 2, 'Mice': 2, 'Dog': 5, 'Duck': 2, 'Hamster': 5}

new_dict = dict()
for k,v in W.items():
    if v in new_dict:
        new_dict[v].append(k)
    else:
        new_dict[v] = [k]

CodePudding user response:

One quick note -- what you're describing isn't a "sort"! A sort is where you have a list like [2, 1, 6, 3] and you turn it into [1, 2, 3, 6] -- what you're doing is more like reversing the keys and values of a dictionary; you're taking the values and using them as keys, and using lists of the keys as values.

Just like you can use for ... in range(...) to iterate over a range, you can use for ... in W to iterate over all the keys in W:

new_Dict = {}  # empty dict
for key in W:
    val = W[key]
    if val not in new_Dict:
        new_Dict[val] = []  # empty list
    new_Dict[val].append(key)

There are other ways to iterate over a dictionary that can make this easier. For example, every dictionary has an items() method that automatically gives you the values as well as the keys:

new_Dict = {}  # empty dict
for key, val in W.items():
    if val not in new_Dict:
        new_Dict[val] = []  # empty list
    new_Dict[val].append(key)

There's also a wonderfully useful thing called collections.defaultdict, which is a dictionary that automatically creates a value where one doesn't exist, of whatever type you want. In this case, we want every value in our new_Dict to start as an empty list, so rather than constantly checking to see if the value is there and creating a new list if it's not, we can make a defaultdict that uses list as its default:

from collections import defaultdict

new_Dict = defaultdict(list)
for key, val in W.items():
    new_Dict[val].append(key)

Bonus preview of what's eventually to come: once you learn about list comprehensions and dict comprehensions, you can build a dict like this in a single line!

new_Dict = {val: [k for k, v in W.items() if v == val] for val in set(W.values())}

CodePudding user response:

Create a new dictionary

sorted_W = {}

Iterate over the key, value pairs.

for key, value in W.items():

if value (animal's value) doesn't exist in the sorted dictionary, then create an empty list (a list because multiple animals can have the same occurrence).

if value not in sorted_W:
    sorted_W[value] = []

Append key (animal name) to the list.

sorted_W[value].append(key)

Complete code:

W = {'Cat': 2, 'Mice': 2, 'Dog': 5, 'Duck': 2, 'Hamster': 5}

sorted_W = {}
for key, value in W.items():
    if value not in sorted_W:
        sorted_W[value] = []
    
    sorted_W[value].append(key)
        
print(sorted_W)
  • Related