Kanthil
Kanthil

Reputation: 1

Simplify nested dictionaries

I took Python as my first programming language and I'm reading the book "Python Crash course". There's an exercise where I need to make dictionaries inside a dictionary and print the info of each city.

I'm using Python 3.7.0. The code below works just intended but I'm trying to find a simpler way to do this. Is there anything I can improve?

cities = {
    'viedma': {
        'provincia': 'rio negro',
        'habitantes': 50000,
        'pais': 'argentina',
        },
    'patagones': {
        'provincia': 'buenos aires',
        'habitantes': 20000,
        'pais': 'argentina',
        },
    'caba': {
        'provincia': 'caba',
        'habitantes': 2800000,
        'pais': 'argentina',
        }
    }

for city, info in cities.items():
    print('\nCiudad: ' + city.title())
    k = list(info.keys())
    v = list(info.values())
    count = 0
    for sub_info in k:
        print(str(sub_info.title()) + ': ' + str(v[count]).title())
        count += 1

Upvotes: 0

Views: 218

Answers (1)

John Kugelman
John Kugelman

Reputation: 361730

The outer loop elegantly iterates over the keys and values in the outer dict. The inner loop should do the same thing. There's no need for the roundabout code to save the keys and values of each inner dict in k and v and then iterate over them with a manual count variable.

for city, info in cities.items():
    print('\nCiudad: ' + city.title())
    for name, value in info.items():
        print(name.title() + ': ' + str(value).title())

Upvotes: 2

Related Questions