Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # assuming you have already created a dictionary like this one
- # tallying word frequencies
- d = {
- 'dog': 4,
- 'cat': 3,
- 'the': 3,
- 'chases': 2,
- 'why': 1
- }
- # method 1
- # most Pythonic, but doesn't "show its work", so a leap of logic needed
- # use max to select the word that has the highest value directly
- # this works by saying 'the key for determining max-ness is d.get,'
- # i.e. what we get when we look up the item in d, i.e. its value.
- # easiest by far in Python but because of its compactness it may be
- # instructive to read the other methods
- most_freq_word = max(d, key=d.get)
- print(most_freq_word)
- # method 2
- # most intuitive
- # iterate through keys, keeping track of the highest value
- highest_freq = 0
- most_freq_word = ''
- for word in d:
- freq = d[word]
- if freq > highest_freq:
- most_freq_word = word
- highest_freq = freq
- print(most_freq_word)
- # method 3
- # invert the dictionary (swap values and keys)
- # then use max() to pick the highest value
- # NOTE: because there can be ties, each new value needs to be a list;
- # here's what it would look like:
- """
- d_inverted = {
- 4: ['dog'],
- 3: ['cat', 'the'], # <-- note the tie here, hence the lists
- 2: ['chases'],
- 1: ['why']
- }
- """
- d_inverted = {}
- for word in d:
- freq = d[word]
- if freq not in d_inverted:
- d_inverted[freq] = []
- d_inverted[freq].append(word)
- highest_freq = max(d_inverted)
- most_freq_word = d_inverted[highest_freq][0] # [0] because it's a list
- print(most_freq_word)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement