Search code examples
dictionarydictionary-comprehension

Parsing through 'mixed' dicitonary


supposed I have the following dictionary with standard and nested key value pairs:

dictionary = {'fruta1': 'Pera',
                  'fruta2': {'fruta3': 'aguacates', 'fruta4':'limones'}
              }

How can I iterate through all the items with a dictionary comprehension? the following code throws this error: "TypeError: can only concatenate str (not "dict") to str" if I try this loop:

texto = '\n'.join(key + ":\n" + value for key, value in dictionary.items())
print(texto)

Any help will be greatly appreciated, thanks.


Solution

  • I think you'd be better off with a recursion:

    dictionary = {'fruta1': 'Pera',
                  'fruta2': {'fruta3': 'aguacates', 'fruta4':'limones'}
                 }
    
    def print_key_val(dic):
       for k,v in dic.items():
          if isinstance(v, dict):
             print_key_val(v)
          else:
             print(f"{k}:\n{v}")
    
    print_key_val(dictionary)
    

    Output:

    fruta1:
    Pera
    fruta3:
    aguacates
    fruta4:
    limones