Home > Software design >  How to get one meaning of a word with PyDictionary?
How to get one meaning of a word with PyDictionary?

Time:10-18

What I am trying to achieve is the ability to choose one random meaning of a word with PyDictionary, using this code:

word = dic.meaning('book')
print(word)

So far, this only outputs a long list of meanings, instead of just one.

{'Noun': ['a written work or composition that has been published (printed on pages bound together', 'physical objects consisting of a number of pages bound together', 'a compilation of the known facts regarding something or someone', 'a written version of a play or other dramatic composition; used in preparing for a performance', 'a record in which commercial accounts are recorded', 'a collection of playing cards satisfying the rules of a card game', 'a collection of rules or prescribed standards on the basis of which decisions are made', 'the sacred writings of Islam revealed by God to the prophet Muhammad during his life at Mecca and Medina', 'the sacred writings of the Christian religions', 'a major division of a long written composition', 'a number of sheets (ticket or stamps etc.'], 'Verb': ['engage for a performance', 'arrange for and reserve (something for someone else', 'record a charge in a police register', 'register in a hotel booker']}

What I have tried to do to give me the first meaning is:

word = dic.meaning('book')
print(word[1])

But doing this, results in this error: KeyError: 1 . If you or anyone knows how to fix this error, please help out by leaving a reply. Thanks in advance :)

CodePudding user response:

dic is returning a dict object, not a list - so you can't use indexes to get the first item.

You can do this instead

word = dic.meaning('book')
print(list(word.values())[0])

Note that in Python and most other languages, counting starts with 0. So the first item in a list is index 0 not 1.

  • Related