Search code examples
pythonloopsdictionaryiteration

Iterating through a dictionary for a specific outcome


I have a dictionary in which the keys represent the categories and their values the item-lists for each category, like so:

d = {category_a: [item_a, item_b, item_c], category_b: [item_d, item_e]}

I want to iterate through the dictionary for the following result:

category_a
· item_a
· item_b
· item_c
category_b
· item_d
· item_e

The formatting with break-lines and such seem to work. My issue is that I only get to the following result:

category_a
· item_a
· item_b
· item_c
· item_d
· item_e
category_b
· item_a
· item_b
· item_c
· item_d
· item_e

I understand that my code (see below) iterates though all items for all keys, which probably causes the issue. Everything else have I tried leads to errors or one-letter-per-line outcome. I want to place the outcome in a PySimpleGUI Multiline. That's why I intend to place it in a string.

Here is my basic code-structure:

def display():

    d = {category_a: [item_a, item_b, item_c], category_b: [item_d, item_e]}
    
    output = ""

    for k in d.keys():
        output += k + "\n"

        for key, val in d.items():
            for v in val:
                output += " · " + v + "\n"

    return output 

I tried, in the second for loop, to only access the values of the key used above (first loop) but can't get it working: Either I only get the item-list - not the items in it - or I produce an error.


Solution

  • Here is the corrected code:

    def display():
    
        d = {'category_a': ['item_a', 'item_b', 'item_c'], 'category_b': ['item_d', 'item_e']}
        
        output = ""
    
        for k in d.keys():    # for k in d:  also works
            output += k + "\n"
            for v in d[k]:
                output += " · " + v + "\n"
    
        return output