pythonfunctionloopsdictionarynumber-sequence

Python Function: Loop Through a "Key:Value" Dictionary And Append The Last "Value" Word To an Output String Based on the Dictionary's Key


Let's say I have the following dictionary:

sorted_dict = {1: 'You', 2: 'teeth', 3: 'are', 4: 'mood', 5: 'test', 6: 'helpful'} 

Each word is associated with a number and I want to arrange the words into a pyramid like the example below:

1
2 3
4 5 6  

The trick here is I only want the words corresponding to the numbers at the end of each line (1, 3, 6). All other words are discarded. So:

1: You
3: are
6: helpful

In the end I want to return a string associated with numbers 1, 3, 6. In my example the desired output would be:

"You are helpful"

I've started trying to write the function for this (see below). But I don't know how to get the pyramid pattern 1, 3, 6 in my loop to get the right words out. Please note this is a small example but I want my function (with this pyramid pattern) to run on a dictionary that potentially has thousands of words.

def test(input_list):
    output_str = ""
    
    i = 1
    
    for key, value in sorted_dict.items():
        
        print(key, value)
        
        # i += ? 
        # if statement here to only append string to output_str if it equals the right i number 
        output_str += ' ' + value
        
    
    return output_str

My current function above returns: ' You teeth are mood test helpful' which is incorrect

How do I fix this?


Solution

  • You don't need to loop through the dictionary. Generate the keys using simple arithmetic, the sequence is 1, 1+2, 1+2+3, and so on. Stop when the key isn't found in the dictionary.

    key = 1
    increment = 2
    output_list = []
    
    while key in sorted_dict:
        output_list.append(sorted_dict[key])
        key += increment
        increment += 1
    
    output_str = " ".join(output_list)