-3

I want to convert my dictionary to a triply ordered reversed dictionary.

my dictionary is {1: 1, 3: 3, 5: 6, 6: 6}

I have already tried using nested dictionaries, but i am not sure how to get the required output.

Dict1 = list(Dict)

Dict2['Dict1'] = Dict

print(Dict2)

The output should be {1: {1: [1], 3: [3]}, 2: {6: [5, 6]}} if i define a different dictionary, i should get different triply ordered dictionary.

Can someone please help me with this?

Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • 4
    good example, but can you explain the logic a bit more? – Chris_Rands Jun 19 '19 at 09:22
  • Please explain with logic how we reach from what you have to `reversed triply ordered dictionary` – Devesh Kumar Singh Jun 19 '19 at 09:26
  • While there is an answer using defualt dict, I suggest checking out this answer to a similar questoin: https://stackoverflow.com/a/485368/6018688 that uses `inv_map.setdefault(v, []).append(k)` and does not rely on defaultdict from collections. – fabianegli Jun 19 '19 at 09:44

1 Answers1

0
from collections import defaultdict

orig_d = {1: 1, 3: 3, 5: 6, 6: 6}

new_d = defaultdict(list)
for k, v in orig_d.items():
    new_d[v].append(k)

final_d = defaultdict(dict)
for cnt, (k, v) in sorted((len(v), (k, v)) for k, v in new_d.items()):
    final_d[cnt][k] = v

print(dict(final_d))

Prints:

{1: {1: [1], 3: [3]}, 2: {6: [5, 6]}}
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91