Search code examples
pythondictionarydictionary-comprehension

How to add multiple values to a multilevel dictionary in python


I tried rubberduckying this, but I give up. I don't understand why this keeps failing me. I have the following dictionary template I want to fill

 testfile = {'locations':
        {'location_name1":
                {'document_title1': 'title_value1',
                'page_nr1': 'text_value1'}
        }}

I have the following code that triest to insert multiple values into it. This represents the code that I'm currently working with.

testfile = {}


locatie = 0


while location != 5:
   page_nr = 0
   while page_nr != 3:
      testfile = testfile + {'location':{'location_naam' + str(location): 
      {'page_nr' + str(page_nr):'text_value'+ str(pagina_nr)}}}
      page_nr += 1
   location += 1

This keeps resulting in the code overwriting testfile every loop. But i want to add the values and basically getting 3 location_names with 5 document_titles/page_nrs per location_name.

How do i achieve this?

EDIT

The desired output would be

{'location': 
   {'location_naam0': {
      'page_nr0': 'text_value0',
      'page_nr1': 'text_value1',
      'page_nr1': 'text_value1'}}, 
   {'location_naam1': {
      'page_nr0': 'text_value0',
      'page_nr1': 'text_value1',
      'page_nr1': 'text_value1'}},
   {'location_naam2': {
      'page_nr0': 'text_value0',
      'page_nr1': 'text_value1',
      'page_nr1': 'text_value1'}},
   {'location_naam3': {
      'page_nr0': 'text_value0',
      'page_nr1': 'text_value1',
      'page_nr1': 'text_value1'}},
   {'location_naam4': {
      'page_nr0': 'text_value0',
      'page_nr1': 'text_value1',
      'page_nr1': 'text_value1'}}
  }

Solution

  • Is this what you want?

    print({
        'location': {
            "location_naam{}".format(i): {
                "page_nr{}".format(k): "text_value{}".format(k)
                for k in range(2)
            }
            for i in range(4) 
        }
    
    })
    
    
    out:
    {
        "location": {
            "location_naam0": {
                "page_nr0": "text_value0",
                "page_nr1": "text_value1"
            },
            "location_naam1": {
                "page_nr0": "text_value0",
                "page_nr1": "text_value1"
            },
            "location_naam2": {
                "page_nr0": "text_value0",
                "page_nr1": "text_value1"
            },
            "location_naam3": {
                "page_nr0": "text_value0",
                "page_nr1": "text_value1"
            }
        }
    }