Jayjay
Jayjay

Reputation: 103

How to sort values in dictionaries

Below is the sample code snippet i want to sort

Variable books is a dictionaries contains values.

books =  {
     1234 : {
      'isbn' : '1234',
      'name' : 'Test Book 1',
      'publish' : 'January 1990'
    },
     2345 : {
      'isbn' : '2345',
      'name' : 'Sample Book',
      'publish' : 'December 2000'
    }

}

for key, values in books.items():
    values.sort(key=lambda x: int(x['name']))

When i compiled the code. I have an error encounntered. 'dict' object has no attribute 'sort'

How can I sort the books by values with the key 'name'

Upvotes: 1

Views: 743

Answers (1)

Chen A.
Chen A.

Reputation: 11280

You need to create an OrderedDict from books, which is a dict that keeps track of the insertion order (like list). This module is sub class of dict, and has sorting functionality. You then can use

>>> OrderedDict(sorted(books.items(), key=lambda x: x[1]))
OrderedDict([(1234, {'isbn': '1234', 'name': 'Test Book 1', 'publish': 'January 1990'}), (2345, {'isbn': '2345', 'name': 'Sample Book', 'publish': 'December 2000'})])

If you don't need it to be a dict, you can use the sorted function and have list of tuples (with dicts inside the items)

Upvotes: 1

Related Questions