-1
{'KRW-SOL': {'count': 3, 'tradeAmount': 437540}, 
'KRW-LOOM': {'count': 78, 'tradeAmount': 21030768}, 
'KRW-ONT': {'count': 14, 'tradeAmount': 947009}, 
'KRW-FCT2': {'count': 1, 'tradeAmount': 491935}, 
'KRW-DKA': {'count': 30, 'tradeAmount': 12053758}

I want to sort by count or tradeAmount

i want like this

{'KRW-LOOM': {'count': 78, 'tradeAmount': 21030768}, 
    'KRW-DKA': {'count': 30, 'tradeAmount': 12053758}
    'KRW-ONT': {'count': 14, 'tradeAmount': 947009}, 
    'KRW-SOL': {'count': 3, 'tradeAmount': 437540}, 
    'KRW-FCT2': {'count': 1, 'tradeAmount': 491935}}
realmasse
  • 523
  • 1
  • 6
  • 18
  • It doesn't make sense for a dictionary to be sorted. If you want to display it like this I think you must implement a custom function to print it in the correct order. But if you need sorted data consider if using an array might be a better option. – Joel Imbergamo Nov 21 '21 at 10:26
  • 1
    @JoelImbergamo It makes perfect sense for a dictionary to be sorted. Dictionaries have had insertion order since Python 3.7 (unofficially in CPython since 3.6). – kaya3 Nov 21 '21 at 10:45

2 Answers2

0
sorted(cdDict.items(), key=lambda item: item[1]['tradeAmount'], reverse=True)
realmasse
  • 523
  • 1
  • 6
  • 18
0

you can do something like below

x  = {'KRW-SOL': {'count': 3, 'tradeAmount': 437540}, 
'KRW-LOOM': {'count': 78, 'tradeAmount': 21030768}, 
'KRW-ONT': {'count': 14, 'tradeAmount': 947009}, 
'KRW-FCT2': {'count': 1, 'tradeAmount': 491935}, 
'KRW-DKA': {'count': 30, 'tradeAmount': 12053758}} #input

# new dict sorted by count
y = {k: v for k, v in sorted(x.items(), key=lambda item: item[1]['count'],reverse=True)}

print(y)

If you want sort by tradeAmount then,

y = {k: v for k, v in sorted(x.items(), key=lambda item: item[1]['tradeAmount'],reverse=True)}

print(y)
Sifat Amin
  • 1,091
  • 6
  • 15
  • You don't need to do `{k: v for k, v in ...}`, the `dict` constructor already takes an iterable of pairs. – kaya3 Nov 21 '21 at 10:45