Dictionaries within a dictionary, python 3


I have a dictionary with lists:

d1 = {
  'frutas': {
     ' manzanas': [' verdes', ' 7', ' rojas', ' 5'],
      'uvas': [' negras', ' 5', ' verdes', ' 3']
   ' verduras': {
      'papa': ['negras', ' 50', ' blancas', ' 20'],
      'cebolla': [' blancas', ' 30']
   'cereales': {
      ' arroz': [' fino',' 600', ' largo', ' 800']

I would like to be able to show with a function each one of the keys with their respective lists, but without showing the contents of the list. So:

frutas : manzanas, uvas
verduras : papa, cebolla
cereales : arroz

** Detail: d1 is loaded from a file.txt on my pc. The function should serve me for any other dX that loads.

asked by Jarni Garay 16.10.2018 в 00:15

2 answers


Considering that you retrieve the data from a file, before converting it to a dictionary in order to manipulate it, the ast module:

def leer():
   archivo= open( ruta_DE_TU_aRChivo, 'r')
   texto= archivo.read()
   #convertir a diccionario
   import ast
   d1= ast.literal_eval( texto)

   # Los diccionarios tienen estos metodos: keys() para obtener las claves, y values():

   for item in d1.keys():

      temp= ','.join(  d1[item].keys()  )
      print(item,":",   temp)
answered by 16.10.2018 / 00:27

Python dictionaries have a couple of methods that may be useful in this case. diccionario.keys() gives you a list with all the dictionary keys. diccionario.items() gives you another list with partners (key, value).

Using both and the str.join() method to concatenate several elements of a list and form a string with them, you can do the following:

for clave, valor in d1.items():
  # La clave sería por ejemplo "frutas", el valor sería en este caso 
  # otro diccionario. Con 'valor.keys()' sacamos la lista
  # de claves de este otro diccionario, que serían los nombres de las frutas
  elementos = ", ".join(valor.keys())
  print(clave, ":", elementos)
frutas :  manzanas, uvas
verduras : papa, cebolla
cereales :  arroz
answered by 16.10.2018 в 09:18