Skip to content

Instantly share code, notes, and snippets.

Created April 20, 2022 19:31
What would you like to do?
Python "dictionary"
#!/usr/bin/env python3
import sys
import requests
from termcolor import colored
from requests.exceptions import JSONDecodeError
from typing import Dict, Union
def make_api_request(word: str) -> Union[Dict, None]:
url = f"{word}"
response = requests.get(url)
if response.status_code != 200:
return None
return response.json()
except JSONDecodeError:
return None
def get_user_input() -> Union[str, None]:
input = sys.argv[1]
if len(input) == 0:
return None
return input
except IndexError:
return None
def main() -> None:
input = get_user_input()
if input is None:
print(colored('Invalid input.', 'red'), file=sys.stderr)
data = make_api_request(input)
if data is None or len(data) == 0:
print(colored('No data for word or word is invalid.', 'red'), file=sys.stderr)
for details in data:
word = colored(details['word'], 'green')
phonetic = colored(details['phonetic'], 'yellow')
except KeyError:
phonetic = ''
for meaning in details['meanings']:
part_of_speech = colored(meaning['partOfSpeech'], 'cyan')
print(f"\n{word} {phonetic} {part_of_speech}\n")
for index, definition in enumerate(meaning['definitions']):
print(f"{index+1}. {definition['definition']}")
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment