0

second try for this question. I already changed 2 suggested answers, but they didn't solved my problem. My dictionary looks like this:

old_list = {
   "x": {
      "bd_date": "04/01/1977",
      "name": "Deli Mirko",
      "next": "04/02/2021",
      "renew": 1,
      "type": "birthday",
      "until": 335
   },
   "y": {
      "bd_date": "25/11/1983",
      "name": "Deli Marina",
      "next": "25/11/2021",
      "renew": 1,
      "type": "birthday",
      "until": 295
   },
   .....
}

I wish to sort it using "until" values ASC.

Is there a way to do this.

I tried suggested solutions, Sort nested dictionary by values Sort nested dictionary by value, and remainder by another value, in Python

but I don't get result OR it changes my dictionary format. I need to keep format, because the rest of code. I tried

new_list = sorted(old_list.items(), key=lambda i: i[1]['until'])

but it changes format to list from dict - [("x",{...}), ("y",{..})...]

So, how to change above code to keep format {"x": {...}, "y": {...}}

This is important because later in code I use loop that outputs data

events_keys = old_list.keys()
     for events_key in events_keys:
           event = old_list[events_key]
           # Get values for each event
           tmp_bd = event['bd_date']
           tmp_name = event['name']
           ....

so I guess I need to sort dict first, so printed values come in increasing order?!

bwanaHA
  • 7
  • 4

1 Answers1

1

Just use dictionary comprehension on your sort result. This works since from Python 3.6 onwards, the standard dict type maintains insertion order by default.

new_list = {k:v for k, v in sorted(old_list.items(), key=lambda i: i[1]['until'])}

new_list:

{'y': {'bd_date': '25/11/1983',
  'name': 'Deli Marina',
  'next': '25/11/2021',
  'renew': 1,
  'type': 'birthday',
  'until': 295},
 'x': {'bd_date': '04/01/1977',
  'name': 'Deli Mirko',
  'next': '04/02/2021',
  'renew': 1,
  'type': 'birthday',
  'until': 335}}
DarrylG
  • 16,732
  • 2
  • 17
  • 23