Home > Blockchain >  how to update nested dictionary types in python
how to update nested dictionary types in python

Time:10-31

I am really a beginner in Python and I wanted to update a nested dictionary.

Here is my code:

players_score= {}

per_round_score = dict()
name =["ram","shyam"]
for k in range(0,len(name)):
    for _ in range(0,2):
        per_round_score[f'round_{k}'] = {k:name[k]}
    players_score.update(per_round_score)
print(players_score)

Output of the code is:

{'round_0': {0: 'ram'}, 'round_1': {1: 'shyam'}}

But I want output as:

{'round_0': {"ram":0 ,"shyam":0}, 'round_1': {"ram":1,'shyam':1}}

CodePudding user response:

zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together etc.

You can try this:

players_score = {}

per_round_score = dict()
name = ["ram", "shyam"]
for k in range(0, len(name)):
    per_round_score["round_"   str(k)] = dict(zip(name, [k for i in range(0, len(name))])))
    players_score.update(per_round_score)

print(players_score)

Output:

{'round_0': {'ram': 0, 'shyam': 0}, 'round_1': {'ram': 1, 'shyam': 1}}

CodePudding user response:

Try using itertools.repeat

from itertools import repeat
name =["ram","shyam"]
{f"round_{i}": dict(zip(name, repeat(i))) for i in range(len(name))}
{f"round_{i}": {n:i for n in name} for i in range(len(name))} # without repeat

# output {'round_0': {'ram': 0, 'shyam': 0}, 'round_1': {'ram': 1, 'shyam': 1}}
  • Related