0

How to sort dictionary inside dictionary?

dic={doc1: {'qq': 5, 'ww': 6, 'gg': 2}, doc2: {'xx': 1, 'cc': 9, 'hh': 4}}

I want it to be like this (sorted desc on values of inner dictionary)

dic={doc1: {'ww': 6, 'qq': 5, 'gg': 2}, doc2: {'cc': 9, 'hh': 4, 'xx': 1}}

I've looked here, but that seems to solve only particular problem. I have thousands of keys (doc3, doc4,...), so I want something more generic.

Thanks

EDIT

I figured it out. Since I can't post solution solution is here:

import operator
for q in dic:
    dummydict=dic[q]
    sorted_d = sorted(dummydict.items(), key=operator.itemgetter(1), reverse=True)
    sortedDic[q]=dict(sorted_d)

I understand that you might say that dictionary will not necessarily preserve its order. I run on 3.6.4, and it preserves

Eric Klaus
  • 923
  • 1
  • 9
  • 24

1 Answers1

0

Try dictionary comprehension:

>>> dic={'doc1': {'qq': 5, 'ww': 6, 'gg': 2}, 'doc2': {'xx': 1, 'cc': 9, 'hh': 4}}
>>> {k:dict(sorted(v.items(),key=lambda x: x[1],reverse=True)) for k,v in dic.items()}
{'doc1': {'ww': 6, 'qq': 5, 'gg': 2}, 'doc2': {'cc': 9, 'hh': 4, 'xx': 1}}
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • It is not generic, that will solve only above 2 keys. I have thousands of keys (doc3,doc4,...,doc1000) – Eric Klaus Sep 25 '18 at 02:01
  • @EricKlaus What do you mean? That code will work on a dictionary containing any number of dictionaries, assuming you run it on Python 3.6+. It won't work on arbitrarily nested dicts, though. – PM 2Ring Sep 25 '18 at 02:06
  • what happens if dict is this? dic={doc1: {'ww': 6, 'qq': 5, 'gg': 2}, doc2: {'cc': 9, 'hh': 4, 'xx': 1},doc3: {'cc': 9, 'hh': 4, 'xx': 1}}. I'll have to add doc3 values too to your script? and then doc4, etc. ? I have thousands of docs, with your solution, script will be million rows length – Eric Klaus Sep 25 '18 at 02:08