Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing double digits from a nested dictionary

I’m having trouble printing out some values from nested dictionary. My nested dictionary looks like this:

player_statistics = {'Johny': {'Kills': '7', 'Assists': '11', 'Deaths': '14'},
                     'Alice': {'Kills': '5', 'Deaths': '7', 'Assists': '3'},
                     'Jim': {'Kills': '14', 'Deaths': '6', 'Assists': '9'}}

I’m supposed to print out each infromation type for each player like this:

Player statistics:

ALICE
Assists: 3
Deaths: 7
Kills: 5
------------
JIM
Assists: 9
Deaths: 6
Kills: 14
------------
JOHNY
Assists: 11
Deaths: 14
Kills: 7
------------

But for some reason I end up having a result like this, where double digits’ second number goes to the next line:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Player statistics:

ALICE:
Assists: 3
Deaths: 7
Kills: 5
------------
JIM
Assists: 9
Deaths: 6
Kills: 1
4
------------
JOHNY
Assists: 1
1
Deaths: 1
4
Kills: 7
------------

Here is my code:

def main():

    player_statistics = {'Johny': {'Kills': '7', 'Assists': '11', 'Deaths': '14'},
                         'Alice': {'Kills': '5', 'Deaths': '7', 'Assists': '3'},
                         'Jim': {'Kills': '14', 'Deaths': '6', 'Assists': '9'}}
    
    print("Player statistics:")
    print()
    for player in sorted(player_statistics):
        print(player.upper())
        for stat_type in sorted(player_statistics[player]):
            print(stat_type, end=": ")
            for value in sorted(player_statistics[player][stat_type]):
                print(value)
        print("------------")


if __name__ == "__main__":
    main()

I believe the issue is caused by the formatting on the line 12. Why does it work like this, instead of just giving the full double-digit value to the end of the stat_type line? Also, how can I make it to work properly?

>Solution :

Instead of this:

for stat_type in sorted(player_statistics[player]):
    print(stat_type, end=": ")
    for value in sorted(player_statistics[player][stat_type]):
        print(value)

It should be something like this:

for stat_type in sorted(player_statistics[player]):
    print(f"{stat_type}: {player_statistics[player][stat_type]}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading