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

Player=Derrick Henry
player 2
Player=Nnikki Chubb
Player=Nikki Chubb

i tried the following code

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():
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

Asked By: lui



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():
    for prop_key, prop_value in props.items():
Answered By: azro

You kinda haven’t really decided yet, if you want to iterate over the nested dict or not. To iterate over it, check azro’s answer. But what you are attempting is not iterating, so you can just write:

print("Player = {}".format(value["Player"]))
print("Yards = {}".format(value["Yards"]))
print("TD = {}".format(value["TD"]))

Or, as the print statements are all the same, you could loop over the keys you want to print:

for key in ["Player", "Yards", "TD"]:
    print("{} = {}".format(key, value[key])
Answered By: treuss
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.