129893289
129893289

Reputation: 3

Returning a dictionary key from its value

So I am trying to write a basic function that takes a text input and an integer 'n', and returns the words in the input that occur n times or more.

Here is what I have:

My problem is the 'return keys' line - clearly that will not work.

What can I use to return the relevant words?

Thanks

Upvotes: 0

Views: 66

Answers (3)

Zulu
Zulu

Reputation: 9265

In Python 2.7, you can revert your dictionary with dict comprehension and after get the key from the value.

For example with a simple dict:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> revert_d = {v: k for k, v in d.items()}
>>> revert_d
{1: 'a', 2: 'b', 3: 'c'}
>>> revert_d[1]
'a'

Upvotes: 0

jh liu
jh liu

Reputation: 72

counttext = collections.Counter(ltext)
result = []
for key in counttext:
    if counttext[key] >= n:
        result.append(key)
return result

Upvotes: 0

grayshirt
grayshirt

Reputation: 643

return [k for k, v in counttext.items() if v >= n]

Upvotes: 2

Related Questions