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

loop through nested dictionary in python and display key value pair

i am a beginner in python i and i came up this problem and i cant seem to solve it.I have the following dictionary

stats = {1: {"Player": "Derrick Henry", "yards": 870, "TD": 9}, 2: {"Player": "Nick Chubb", "Yards": 841, "TD": 10}, 3: {"Player": "Saquon Barkley", "Yards": 779, "TD": 5}}

I want to loop through a dictionary and display the values as shown below

Player1
Player=Derrick Henry
yards=870
TD=9
player 2
Player=Nnikki Chubb
yards=770
TD=10
player3
Player=Nikki Chubb
yards=770
TD=10

i tried the following code

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

stats = {1: {"Player": "Derrick Henry", "Yards": 870, "TD": 9}, 2: {"Player": "Nick Chubb", "Yards": 841, "TD": 10}, 3: {"Player": "Saquon Barkley", "Yards": 779, "TD": 5}}

for key, value in stats.items():
    print(value)
for x, y,z in value.items():
        print("Player {}".format(key))
        #IF Player
        if x == "Player":
            print("Player = {}".format(x))
        #IF YARDS
        if y == "Yards":
            print("Yards = {}".format(y))
        #IF YARDS
        if z == "TD":
            print("yards = {}".format(y))

Any help will be appreciated.Thank you

>Solution :

Don’t you see here the useless logic : if a variable is something, you write manualmy that thing in a string, just use it directly

if x == "Player":
    print("Player = {}".format(x))
if y == "Yards":
    print("Yards = {}".format(y))
if z == "TD":
    print("TD = {}".format(y))

Also you did well use .items first time, but misuses it the second time, it iterate over pair, so it’ll always yields 2 variable , not 3

for key, props in stats.items():
    print(f"Player{key}")
    for prop_key, prop_value in props.items():
        print(f"{prop_key}={prop_value}")
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