Home > Software engineering >  Trying to create a new dictionary through for and if loops
Trying to create a new dictionary through for and if loops

Time:11-26

I'm trying to write a loop that will iterate through a list of four-letter words, take the last two letters of the word, and assign the word to a dictionary key based on the last two letters. This is what I've got so far:

dictionary = {}

for z in four_letters: #For each element of the four_letters list 
    last_letters = getLastLetters(z) #Get the last to letters from the word
    if last_letters not in dictionary.keys(): #If the last two letters have not already been made into a key in the dictionary...
        dictionary[last_letters] = z #Create a key and add the word as a value
    else: #If it has...
        dictionary[last_letters].append(z) #Just add the word to the list of values

When I print the dictionary, there is only one value per key and I was wondering if anyone could explain what I've done wrong and help me correct it. Thanks in advance.

CodePudding user response:

The problem is in the line:

dictionary[last_letters] = z

It should have been:

dictionary[last_letters] = [z]

But here is a better (performant and some what cleaner) solution you should consider.

dictionary = {}

four_letters = [
    "dfdf",
    "df2f",
    "d1df",
    "d3df",
    "d4df",
    "d5df",
    "d6df",
    "df6f",
    "df4f",
]

def getLastLetters(word):
    return word[2:]

for word in four_letters: #For each element of the four_letters list 
    last_letters = getLastLetters(word) #Get the last to letters from the word
    try:
        dictionary[last_letters].append(word)
    except KeyError:
        dictionary[last_letters] = [word]

print(dictionary)

Sample output:

{'df': ['dfdf', 'd1df', 'd3df', 'd4df', 'd5df', 'd6df'], '2f': ['df2f'], '6f': ['df6f'], '4f': ['df4f']}

CodePudding user response:

You can set a default value for each key using dict.setdefault(key, value):

def get_last_two_letters(word: str):
    return word[len(word) - 2:]


def build_word_dict(four_letters: [str]):
    word_dict = {}
    for z in four_letters:
        last_two_letters = get_last_two_letters(z)
        word_dict.setdefault(last_two_letters, []).append(z)

    return word_dict


def test_build_word_dict():
    four_letters: [str] = ["hell", "bold", "disc", "clap", "ball"]
    word_dict = build_word_dict(four_letters)

    assert word_dict == {
        "ll": [
            "hell",
            "ball"
        ],
        "ld": [
            "bold"
        ],
        "sc": [
            "disc"
            ],
        "ap": [
            "clap"
        ]
    }

  • Related