2

In my previous question, I found out how to drag some of my co - worker's scores together in a dictionary in the post Reading data separated by colon per line in Python. Now, if I want to arrange the dictionary so that the keys are in order of name, so Adam, Dave and Jack's scores would appear in that order.

I have used the method below:

sorted(self.docs_info.items)

But that returns nothing. I also want it to be returned to the IDLE in the format

Adam 12 34
Dave 25 23
Jack 13

I tried to use the pprint method, but that didn't work either. How can I fix this?

My previous code (finished) appeared like this:

from collections import defaultdict
d = defaultdict(list)
with open('guesses.txt') as f:
    for line in f:
        name,val = line.split(":")
        d[name].append(int(val))

With Credit to Padraic Cunningham and Antti Haapala!

Community
  • 1
  • 1
Delbert J. Nava
  • 121
  • 1
  • 9

2 Answers2

4

Just sort the keys and use the key to access the value:

for k in sorted(d):
    print(k,d[k])

Adam [12, 34]
Dave [23, 25]
Jack [13]

To get the strings use str.join:

for k in sorted(d):
    print(k," ".join(map(str,d[k])))

Adam 12 34
Dave 23 25
Jack 13

calling sorted on the dict is the same as calling sorted on dict.keys() so we just need to use the each now sorted key from the list to access in the required order.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
2
>>> for name, values in sorted(d.items(), key=lambda x: x[0]):
...     print("%s %s" % (name, " ".join(map(str, values))))
...
Adam 12 34
Dave 25 23
Jack 13
Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130