''' Purpose: access the babelfish dictionary ''' # get access to url support import url # Dictionary Recap # Empty dictionaries are initialized with {} # Dictionaries are a collection of keys and values # {key:value, key:value, key:value, ...} # Each key:value pair is called a MAPPING # Creating a new mapping in our dictionary looks like this: # dict_name[key] = value (you fill in the dictionary name, key, and value) # dict_name.get( key ) -> gives you value if key is in the dictionary; None otherwise # dict_name[key] -> gives you value if key is in the dictionary; error otherwise # translation dictionary url -- entries are in csv form; i.e., word,translation BABELFISH_URL = 'http://www.cs.virginia.edu/~cs1112/datasets/words/babelfish' # get contents of babel fish url as a dataset dataset = url.get_dataset( BABELFISH_URL ) print( dataset ) # put entries into a dictionary - a mapping of words to translations # the dictionary starts off empty translation_dictionary = {} # Accumulator for dictionaries (we add mappings to this) # add each word-translation pair to the dictionary for row in dataset : # Dataset is a list of lists (each inner list is a 2 element list) # get the two cells making up the row (the first element in the small list is the key and the second element is the value) key, value = row # .split() is for strings! We can say key, value = row since row is already a list # Alternative # key = row[0] # value = row[1] # print( 'key=', key, 'value=', value ) # use the cells to add an entry to the dictionary translation_dictionary[ key ] = value # Take the value of the defined key and value and add that mapping into our dictionary # Remember that dictionaries cannot have duplicate keys # If you redefine a mapping with the same key, that mapping is replaced with the new key:value mapping # aka if you had dict_name['a'] = 'a' # then you had dict_name['a'] = 'to' # The mapping in the dictionary for that key will be 'a': 'to' (whichever one is the most recent mapping) # dump the dictionary print( translation_dictionary )