简体   繁体   中英

How to sort dictionary in alphabetical order?

I'm doing an exercise where given a CSV file message.csv (the first three lines of which are displayed below), I need to write a program to count the number of messages from each sender, then print the output in alphabetical order by sender.

Sender,Message
"hello there!"
"Computing is damn hard!"

This is what I have tried so far:

from collections import defaultdict
import csv
counting = defaultdict(int)
for row in csv.reader(open(message.csv)):
    counting[row[0]] += 1

I'm stuck on how to continue.

Your code looks like it assumes that the first value of each line is the sender but the 3 lines of the .csv file you've given us don't comply with this.

Based on the actual first 3 lines of the csv file, I would do:

sender = None
for row in csv.reader(open(message.csv)):
    if len(row) == 2:
        sender = row[0]
    counting[sender] += 1

and then as Jim Dennis says, but you shouldn't call .keys() explicitly:

for sender in sorted(counting):
    print sender, counting[sender]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM