Iterating over key/value pairs in a dict sorted by keys

后端 未结 2 1576
灰色年华
灰色年华 2021-02-03 17:31

I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys):

for word, count in sorted(count_words(filename).items()         


        
2条回答
  •  日久生厌
    2021-02-03 17:36

    As per Marks answer: In Python 2, use iteritems(), in Python 3 use items().

    And additionally; If you need to support both (and don't use 2to3) use:

    counts = count_words(filename)
    for word in sorted(counts):
         count = counts[word]
    

提交回复
热议问题