Search code examples
pythonlistdictionarylist-comprehension

Have to create a huge complicated list comprehension to create dictionary of list of ASCII values in Python, cannot use for loop outside of list comp


The following is my code so far along with the instructions in a docstring.

def get_word_codes(words):
"""Given a list of words, return a dictionary where the words are keys,
    and the value for each key is a list of the character codes of the
    letters of the word that is its key."""
[print(ascii(words.index(x))) for x in word in words]

Obviously, this code is wrong, but I have worked on it for hours. I know I seem pathetic, but in my defense, my teacher wants me to print the entire code in just one list comprehension. Obviously, she says that for this exercise, she wants us to use PEP8 as a guide. And I know how I need to split up the code into several lines to make it more readable and presentable. That's not a problem. The problem is I am pretty sure that this list comprehension will be ridiculously long. Please, please help. I am very grateful for any help you can give. Here's how the function should work, if it works correctly:

words = ['yes', 'no']

codes = get_word_codes(words)

codes {'yes': [121, 101, 115], 'no': [110, 111]}

words = ['hello', 'python', 'bye']

codes = get_word_codes(words)

codes {'hello': [104, 101, 108, 108, 111], 'python': [112, 121, 116, 104, 111, 110], 'bye': [98, 121,
101]}

codes = get_word_codes(['Python is fun!'])

codes {'Python is fun!': [80, 121, 116, 104, 111, 110, 32, 105, 115, 32, 102, 117, 110, 33]}

So each word in the list is turned into a key, and each letter in each word is the value, but the value should be the ASCII value of the letter.


Solution

  • You can use list comprehension for dictionaries. Iterate through your list to separate words. Then use list comprehension inside to build a list of ascii values with ord().

    def get_word_codes(words):
        """Given a list of words, return a dictionary where the words are keys,
        and the value for each key is a list of the character codes of the
        letters of the word that is its key."""
        return {word:[ord(x) for x in word] for word in words}
    
    print(get_word_codes(["this", "is", "a", "list", "of", "words"]))
    

    Output:

    {'this': [116, 104, 105, 115], 'is': [105, 115], 'a': [97], 'list': [108, 105, 115, 116], 'of': [111, 102], 'words': [119, 111, 114, 100, 115]}