-5

I am new to Python, I have seen many examples but not a good summary of examples. Here are the 4 things that I want to get done. Thanks for your help.

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

I wanted to use the following to access the dict elements:

for key in sorted(mydict.keys()):
    print(key, mydict[key])

How do I get the following output:

Case 1: (by key ascending)

alan   2
bob    1
carl  40
danny  3

Case 2: (by key descending)

danny  3
carl   40
bob    1
alan   2

Case 3: (by value ascending)

bob   1
alan  2
danny 3
carl 40

Case 4: (by value descending)

carl   40
danny   3
alan    2
bob     1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
userDSSR
  • 627
  • 1
  • 8
  • 17
  • 3
    Turn your eyes a bit towards the right. You'll find several questions that answer this. – devnull May 06 '14 at 19:58
  • 1
    @devnull I've always wondered how the StackOverflow search is so bad, but there are always so many very relevant 'related' questions in the sidebar. – anon582847382 May 06 '14 at 20:00
  • @AlexThornton I agree that the search is not only bad, it's _too bad_. However, the fact that relevant 'related' questions appear on the right exhibits that the same questions are asked over and over. – devnull May 06 '14 at 20:01

2 Answers2

1

See the documentation for sorted.

Ascending by key:

for key, value in sorted(mydict.items()):
    pass

Descending by key:

for key, value in sorted(mydict.items(), reverse=True):
    pass

Ascending by value:

def get_value(item):
    return item[1]

for key, value in sorted(mydict.items(), key=get_value):
    pass

Descending by value:

for key, value in sorted(mydict.items(), key=get_value, reverse=True):
    pass

You could also use key=lambda x: x[1] instead of defining a get_key function if you wanted.

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
0
d = {'carl':40,
      'alan':2,
      'bob':1,
      'danny':3}

ks = sorted(d.keys()) #  sort keys
for key in ks:# key ascending
print(key, d[key])


for key in ks[::-1]: #key descending
    print(key, d[key])


vs= sorted(d, key=d.get) # sort keys by values
for key in vs: # values ascending
    print(key, d[key])


for key in vs[::-1]: # values descending
    print(key, d[key])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321