-4

I need to sort the following dictionary by age but I don't figure how:

1 {'name':'ste',   'surname':'pnt',  'age':21}
2 {'name':'test',  'surname':'black','age':24}
3 {'name':'check', 'surname':'try',  'age':41}

This is the output of a for cycle:

for k, v in d.items():
    print(k, v)
martineau
  • 119,623
  • 25
  • 170
  • 301
S. Pnt
  • 7
  • 3
  • 1
    You can not sort a dictionary, there is no "order" in which dictionary objects appear. Think of it like trying to sort a mathematical set object, it does not make sense. You can read up about this phenomenon more by Googling "why are dictionaries unordered in Python". – Ziyad Edher Mar 20 '18 at 22:08
  • 3
    I don't know what you're trying to show us, but it doesn't look like a dictionary. – user2357112 Mar 20 '18 at 22:08
  • @ZiyadEdher i know dictionaries are unordered, it's fine to get a sorted list or tuple – S. Pnt Mar 20 '18 at 22:11
  • @user2357112 It seems to be a dictionary of dictionaries. – JohanL Mar 20 '18 at 22:12
  • 1
    [Read the Fine Manual](https://docs.python.org/dev/library/functions.html#sorted) (especially the description of `key`). – greybeard Mar 20 '18 at 22:28
  • 3
    Possible duplicate of [How do I sort a list of dictionaries by values of the dictionary in Python?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – greybeard Mar 20 '18 at 22:33

2 Answers2

1
d = {
  1 : {'name':'ste',   'surname':'pnt',  'age':21},
  2 : {'name':'test',  'surname':'black','age':24},
  3 : {'name':'check', 'surname':'try',  'age':41},
}

sorted(d.values(),key=lambda it: it['age'])
-2

So your dictionary is already sorted by age, but...

for key in sorted(mydict.iterkeys()):
    print "%s: %s" % (key, mydict[key])

https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/