-2

I have this Python Code:

def dictofvalues():
    values = {'A': '1', 'C': '3', 'B': '2'}
    return(values)

def main():
    values = dictofvalues()
    print(sorted(values))

Which prints: A, B, C.

However, I want it to print A:1, B:2, C:3. In other words, I want it to print the item with the assigned value as well.

How does one go about doing this?

  • If you want it to be sorted on the keys, the easiest/most straightforward way is just to create a for loop: `for key in sorted(values): print("{}: {}".format(key, values[key]))`. –  May 25 '17 at 03:56
  • 1
    Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – pvg May 25 '17 at 03:58
  • Genius. Works perfectly. Thanks a lot for that one :) – Investigative Moth May 25 '17 at 04:08
  • Perhaps equally genius would have been simply searching. It's one of the most answered answers out there. – pvg May 25 '17 at 04:25

2 Answers2

0

Simply print out the dictionary as a list of tuples:

def dictofvalues():
    values = {'A': '1', 'C': '3', 'B': '2'}
    return(values)

def main():
    values = dictofvalues().items()
    print(sorted(values))
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Also works perfectly, no issues here. Thanks for this method, a special thanks for the actual code! :D – Investigative Moth May 25 '17 at 04:09
  • @InvestigativeMoth no problem, feel free to accept this answer by clicking the green check to give both of us reputation and inform the community that you have found a satisfactory answer – A.J. Uppal May 25 '17 at 04:19
0

You can use OrderedDict from module collections:

from collections import OrderedDict

def dictofvalues():
    values = {'A': '1', 'C': '3', 'B': '2'}
    return(values)

def main():
    values = dictofvalues()
    print(OrderedDict(sorted(d.items())))

I hope it helps,

Nicolas M.
  • 1,472
  • 1
  • 13
  • 26