0

The dictionary contains the following values ​​with names and age of different people. I must order this dictionary from least to greatest in a list. That is, the index 0 must occupy it ('JOHN', 1) and the -1 must occupy it ('RYAN', 25).

dictionary = {1: ('RYAN', 25), 2: ('WILL', 12), 3: ('JOHN', 1), 4: ('MATT', 15),
              5: ('FILL', 19), 6: ('NICK', 4)}
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) and [How to sort (list/tuple) of lists/tuples by the element at a given index?](https://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) – wjandrea Apr 06 '20 at 01:36
  • I might have misunderstood the "dictionary sorting" part. See this instead: [How can I get list of values from dict?](https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict) – wjandrea Apr 06 '20 at 01:39

1 Answers1

2

Talking about an index of a dictionary doesn't make much sense. If you want an index, you should make a list. You can make a list of values() and sort that with a key. For example:

d = {1:('RYAN',25),2:('WILL',12),3:('JOHN',1),4:('MATT',15),5:('FILL',19),6:('NICK',4)}

list(sorted(d.values(), key = lambda x: x[1]))

Result:

[('JOHN', 1),
 ('NICK', 4),
 ('WILL', 12),
 ('MATT', 15),
 ('FILL', 19),
 ('RYAN', 25)]

If you really need a dict, you can pass this list back to OrderedDict() (or dict() in newer versions of python that preserve order), but you won't be able to index it with zero or -1 unless you pull out the values or keys and convert those to a list:

from collections import OrderedDict

d = {1:('RYAN',25),2:('WILL',12),3:('JOHN',1),4:('MATT',15),5:('FILL',19),6:('NICK',4)}

od = OrderedDict(sorted(d.values(), key = lambda x: x[1]))

od.keys()
# odict_keys(['JOHN', 'NICK', 'WILL', 'MATT', 'FILL', 'RYAN'])
Mark
  • 90,562
  • 7
  • 108
  • 148