Home > other >  loop through nested dictionary in python and display key value pair
loop through nested dictionary in python and display key value pair

Time:11-21

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

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

CodePudding user response:

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}")

CodePudding user response:

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])
  • Related