Home > Software design >  Parsing through 'mixed' dicitonary
Parsing through 'mixed' dicitonary

Time:11-22

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.

CodePudding user response:

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
  • Related