1

I have a dict like so:

my_dict = {'hello':'2' , 'foo':'1' , 'foobar':'3'}

I don't want to modify the dict in any way, I just want to iterate through it from the smallest sized key to the largest sized key like so...

for key in my_dict:
    print(my_dict[key])

# Results
# 1
# 2
# 3
Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 2
    Do you mean sorted by length of the key? Then `for key in sorted(my_dict, key=len):` – John La Rooy Sep 08 '14 at 13:24
  • 1
    I'm not trying to sort by value, I'm trying to sort by length of key, please reopen the question. – Ogen Sep 08 '14 at 13:25
  • @gnibbler Thank you gnibbler that works, I'd accept your answer but this question has been marked as a duplicate for no reason... – Ogen Sep 08 '14 at 13:26
  • @Ogen In that case simply replace `dict1.get` with `len` in this answer: http://stackoverflow.com/a/3177911/846892 Ah! gnibbler already posted that. – Ashwini Chaudhary Sep 08 '14 at 13:27
  • @AshwiniChaudhary What if another user wants to achieve what I'm doing. It would be more convenient for them to be able to just search this question rather than searching a related question then connecting the dots. – Ogen Sep 08 '14 at 13:28
  • @Ogen Instead of ranting here learn to use Google: https://www.google.co.in/search?q=how+to+sort+a+dictionary+by+value+in+python – Ashwini Chaudhary Sep 08 '14 at 13:32
  • @AshwiniChaudhary This particular question hasn't been asked on stack overflow, only variants of it. You'd know that if you spent some time looking instead of blindly marking it as a duplicate – Ogen Sep 08 '14 at 13:34
  • @AshwiniChaudhary You should probably put that link as the duplicate instead of the sorting by value one that's currently there. – Ogen Sep 08 '14 at 13:39
  • @Ogen I've re-opened and closed the question again as the more suitable duplicate – Jon Clements Sep 08 '14 at 14:23

1 Answers1

2

You can use the following snippet

for key in sorted(my_dict, key = len):
    print my_dict[key]
1
2
3

The len above is the len function, which means all the entries in my_dict.keys() will be sorted by length, and then their values will be printed

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186