Bokan23
Bokan23

Reputation: 9

compact version of the dictionary

Wrote a function, it creates a modified dictionary:

  d1 = {1 : 2, 3 : 4, 5 : 4, 7 : 2, 9 : 4}
  def swap_dict (d):
    rd = {}
    for k, v in d.items():
      rd[v] = rd.get(v, []) + [k]
    return rd
  print(swap_dict(d1))

How to make the function create a compact version of the dictionary. One word, keys are grouped by source value in tuples.

Example:

dictionary: {1: 2, 3: 4, 5: 4, 7: 2, 9: 4}

compressed into: {(3, 9, 5): 4, (1, 7): 2}

Upvotes: 0

Views: 342

Answers (1)

Francis Colas
Francis Colas

Reputation: 3647

You're almost there; you can simply do:

>>> {tuple(v): k for k, v in swap_dict(d1).items()}                        
{(1, 7): 2, (3, 5, 9): 4}

This is a dict comprehension that is simply building a mapping between your list of keys and the values from the swapped dictionary. More precisely, as keys of a dictionary need to be immutable, it is making a tuple out of your list.

Upvotes: 2

Related Questions