Home > Blockchain >  How to make a dictionary of dictionaries with same keys in a loop
How to make a dictionary of dictionaries with same keys in a loop

Time:05-15

Hello i'm new to python and i'm trying to make a dictionary that can contain multiple dictionaries (depending on how many the user wants) and each dictionary has the same keys as the previous one. with an output similar to this :

{0: {'Name': 'test1', 'Matiere': ['algo','python'], 'Notes': [[11,12],[15,13]}, 
 1: {'Name': 'test2', 'Matiere': ['algo'], 'Notes': [[11]]}}

but what i'm getting is that the values of the 2nd dictionary are overwriting the first one's and i'm left with an output like this :

{0: {'Name': 'test2', 'Matiere': ['algo'], 'Notes': [[11]}}, 
 1: {'Name': 'test2', 'Matiere': ['algo'], 'Notes': [[11]]}}

Here's my code :

def ajout():
    TS = int(input("Donner le nombre d'etudiants: "))
    tmp=[]
    for i in range(TS):
        Student['Name']=input(f"Donner le nom de L'etudiant n{i 1}: ")
        x=int(input("Donner le nombre de matieres : "))
        for j in range(x):
            tmp.append(input(f"Donner la matiere n{j 1}: "))
        Student['Matiere']=tmp
        tmp=[]
        tmp1=[]
        for j in range(len(Student['Matiere'])):
            y=int(input(f"Donner le nombre de notes du {Student['Matiere'][j]}: "))
            for k in range(y):
                tmp.append(int(input(f"Donner la note n{k 1}: ")))
            tmp1.append(tmp)
            tmp=[]
            Student['Notes']=tmp1
        print(Student)
        Students[i]={}
        Students[i]=Student
    print(Students)
ajout()

What Can I change to make it not overwrite the values, but instead have different values depending on what the user types.

PS : here's an image of the

Code's execution

CodePudding user response:

I suppose you initialized Student outside of ajout' scope.

Hence, each time you do Students[i]=Student the same variable is added to the dict, erasing the new one you instantiate with Students[i]={}. As Student is always the same underlying dict structure, each elements in Students are actually referencing only on dict. This also explain why doing Student['whatever'] = ... is modifying every element of Students.

Try inserting Student = {} somewhere at the beginning of ajout ;)
On a side note, there is few useless tmp=[], you only need one here !

  • Related