0

I'm having some trouble with this Python. I'm trying to sort a dictionary alphabetically, from min to max (with values) and from max to min (by values). How can I do this?

Note: I can't get max to min working

stocks = {
    'GOOG': 520.24,
    'FB': 331.28,
    'XMZN': 89.72,
    'APPL': 112.31
}

# for min to max
print(sorted(zip(stocks.values(), stocks.keys())))

# for alphabetically
print(sorted(zip(stocks.keys(), stocks.values())))

# for max to min
print(sorted(zip(stocks.values(), stocks.keys(), reverse))
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 1
    Possible duplicate of [Python list sort in descending order](http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order) – The6thSense Oct 14 '15 at 06:59

3 Answers3

4

Keyword arguments must be given a value, otherwise the identifier will be used as a name.

print(sorted(zip(stocks.values(), stocks.keys(), reverse=True))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • up voted but possible duplicate of [this](http://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order/4183540#4183540) :p – The6thSense Oct 14 '15 at 06:58
2
stocks = {
'GOOG': 520.24,
'FB': 331.28,
'XMZN': 89.72,
'APPL': 112.31
}

print sorted(stocks.items(),key=lambda x:x[1],reverse=True)

You can simply do this instead of zip and all

vks
  • 67,027
  • 10
  • 91
  • 124
1

You can reverse the list using [::-1]

# for max to min
print(sorted(zip(stocks.values(), stocks.keys()))[::-1])

Output:

[(520.24, 'GOOG'), (331.28, 'FB'), (112.31, 'APPL'), (89.72, 'XMZN')]
Avión
  • 7,963
  • 11
  • 64
  • 105