Skip to content
This repository was archived by the owner on May 7, 2023. It is now read-only.

Files

Latest commit

 

History

History
32 lines (27 loc) · 795 Bytes

collect-dictionary.md

File metadata and controls

32 lines (27 loc) · 795 Bytes
title type tags cover dateModified
Invert dictionary
snippet
dictionary
working-bee
2020-11-02 19:27:07 +0200

Inverts a dictionary with non-unique hashable values.

  • Create a collections.defaultdict with list as the default value for each key.
  • Use dictionary.items() in combination with a loop to map the values of the dictionary to keys using dict.append().
  • Use dict() to convert the collections.defaultdict to a regular dictionary.
from collections import defaultdict

def collect_dictionary(obj):
  inv_obj = defaultdict(list)
  for key, value in obj.items():
    inv_obj[value].append(key)
  return dict(inv_obj)
ages = {
  'Peter': 10,
  'Isabel': 10,
  'Anna': 9,
}
collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] }