-2

If I had a list of dictionaries:

[{'name':a,  'number':b,  'blah':c,  'swag':d},
 {'name':a_1,'number':b_1,'blah':c_1,'sw‌​ag':d_1},
 {'name':a_2,'number':b_2,'blah':c_2,'swag':d_2}] 

How would I print all the 'name' values in alphabetical order and the 'number' values in descending order? And let's say the 'a' values are strings, and the 'b' values are integers. How would I print all the 'name' values in alphabetical order and the 'number' values in descending order?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Swandrew
  • 53
  • 1
  • 4

3 Answers3

1

You can sort a list using the builtin "sorted" function. And you can extract the names and the numbers using list comprehension. Combining the two:

>>> dict_list = [{'name':a,'number':b,'blah':c,'swag':d},{'name':a_1,'number':b_1,'blah':c_1,'sw\U+200C​ag':d_1},{'name':a_2,'number':b_2,'blah':c_2,'swag':d_2}]
>>> sorted_names = sorted([d['name'] for d in dict_list])
>>> sorted_names
['a', 'a_1', 'a_2']
>>> sorted_numbers = sorted([d['number'] for d in dict_list], reverse=True)
>>> sorted_numbers
[3, 2, 1]
linus
  • 336
  • 1
  • 9
0

To sort the dict by 'name' in ascending/alphabetical order and then (for those dict who have the same 'name') by 'number' in descending order,

first sort 'number' in descending order

list_of_dict_by_numbers = sorted(original_list_of_dict, key=lambda d: d['number'], reverse=True)

or

list_of_dict_by_numbers = sorted(original_list_of_dict, key=lambda d: -d['number'])

Then sort 'name' in ascending/alphabetical order

result = sorted(list_of_dict_by_numbers, key=lambda d: d['name'])

Since python sort is stable, those dict records who have the same 'name' will retain their 'number' in the sorted descending order.

How to sort in Python

SYK
  • 644
  • 6
  • 17
0

Check the documentation for Python's sorted function:

https://wiki.python.org/moin/HowTo/Sorting

Make sure to read the part about keys!