0

So I have a dictionary, with keys and values, and the values are letters. I want to sort the dictionary so that it prints alphabetically according to the values, but I just can't figure out how to go about it.

For example, I have this dictionary:

dict = {5 : 'B', 7 : 'A', 9 : 'C'}

How do I get this to be sorted so that it prints out as follows?:

{7 : 'A', 5 : 'B', 9 : 'C'}
j.izzy
  • 1
  • 1
  • That output is impossible, you can only have each key once. `dict` (don't name dictionaries `dict`) only contains one key-value pair. – jonrsharpe Dec 07 '17 at 21:17
  • `dict` objects are inherently unordered - it doesn't make sense to say "a sorted dict" – juanpa.arrivillaga Dec 07 '17 at 21:18
  • 1
    Your dictionary itself is invalid.There can only be one key with the value `1` not three of them. – DollarAkshay Dec 07 '17 at 21:18
  • Sorry everyone. it was a typo. I made it so the keys are all different. – j.izzy Dec 07 '17 at 21:20
  • I'm a newbie, im sorry. Basically, i just want the values to be in alphabetical order, and have no idea on how to go about this. – j.izzy Dec 07 '17 at 21:21
  • A bad question maybe, but answering is as much effort as telling you about that. `sorted(d.items(), key=lambda x: x[1]) -> [(7, 'A'), (5, 'B'), (9, 'C')]` – Turksarama Dec 07 '17 at 21:22
  • @j.izzy again, *`dict` objects don't have an order*. It makes no sense to say "I want the dict to be in order" – juanpa.arrivillaga Dec 07 '17 at 21:29
  • @Turksarama thank you! That's along the lines of what I was asking. Sorry i understand why my question is formatted incorrectly now D: – j.izzy Dec 07 '17 at 21:34
  • @turksarama when i use this method, it sorts the keys, and not the values. how do i get it to sort the values? – j.izzy Dec 07 '17 at 21:35
  • @Turksarama never mind! That method fixed my problem. Thank you so much!! – j.izzy Dec 07 '17 at 21:38

1 Answers1

0

Dicts are unsorted, if you need something in a certain order for sure, use a list. Also, you can't duplicate keys.

to make a list:

your_list=['B','A','C']
#yay, now sort
your_list.sort()
SuperStew
  • 2,857
  • 2
  • 15
  • 27
  • Okay. How would I go about changing this to a list, and then sorting by the values, aka the letters? – j.izzy Dec 07 '17 at 21:18
  • 1
    There are other ordered data structures in Python besides lists (for example, a closer fit to a dictionary but with order might be an... [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict)?) – jonrsharpe Dec 07 '17 at 21:19
  • @j.izzy I updated to show the list part – SuperStew Dec 07 '17 at 21:21