Last active
November 13, 2017 10:35
-
-
Save jaycody/d10f161e740f899c6049ce97bb3d931f to your computer and use it in GitHub Desktop.
Basic patterns for sorting dicts by keys or values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""With dictionary d, of format key: word from text, value: word frequency | |
Sort and display the key value pairs in the following ways: | |
1. DISPLAY TOP 20 WORDS & THEIR FREQ - SORTED: MOST FREQUENT FIRST | |
2. DISPLAY ALL WORDS THAT APPEAR MORE THAN 25 TIMES & THEIR COUNT - SORTED: MOST FREQ FIRST | |
3. DISPLAY ALL WORDS - SORTED ALPHABETICALLY | |
""" | |
d = make_wordcount_dict_from(filename) | |
top_twenty_count = 0 | |
####################################################### | |
# SORT BY VALUE - found in x[1] of k, v tuple | |
g = sorted(d.items(), key=lambda x: x[1], reverse=True) | |
####################################################### | |
for k, v in g: | |
# 1. DISPLAY TOP 20 WORDS & THEIR FREQ - SORTED: MOST FREQUENT FIRST | |
if top_twenty_count < 20: | |
print '\t{:8s} --> {}'.format(k, v) | |
top_twenty_count += 1 | |
# 2. DISPLAY ALL WORDS THAT APPEAR MORE THAN 25 TIMES & THEIR COUNT - SORTED: MOST FREQ FIRST | |
if v > 25: | |
print '\t{:8s} --> {}'.format(k, v) | |
## | |
# 3. DISPLAY ALL WORDS - SORTED ALPHABETICALLY | |
####################################################### | |
# SORT BY KEY (word) - ALPHABETICALLY | |
g2 = sorted(d.iteritems()) | |
####################################################### | |
for k, v in g2: | |
print '\t{:8s} --> {}'.format(k, v) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment