[Python] Why get unexpected dict

Discussão em 'Python' iniciado por Stack, Janeiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have a data table as below:

    A B C
    type1 A1 B1 C1
    type2 A2 B2 C2


    I use the code below

    d={}
    D={}
    h = ['A','B','C']
    type1=['A1','B1','C1']
    type2=['A2','B2','C2']

    for i,val in enumerate(h):

    d['Type1'] = type1
    d['Type2'] = type2
    D[val]=d
    print('loop',i,'\nd:',d,'\nD:',D,'\n\n====')

    #print(D)


    I would expect to get the following dict as result:

    {'A':{'Type1':'A1','Type2':'A2'},'B':{'Type1':'B1','Type2':B2},'C':{'Type1':C1,'Type2':'C2'},}


    However, the output is:

    {'A': {'Type1': 'C1', 'Type2': 'C2'}, 'B': {'Type1': 'C1', 'Type2': 'C2'}, 'C': {'Type1': 'C1', 'Type2': 'C2'}}


    What's the error in my logic?

    I can't figure out what's wrong there.

    I added a print in the loop.

    loop 0
    d: {'Type1': 'A1', 'Type2': 'A2'}
    D: {'A': {'Type1': 'A1', 'Type2': 'A2'}}

    ====
    loop 1
    d: {'Type1': 'B1', 'Type2': 'B2'}
    D: {'A': {'Type1': 'B1', 'Type2': 'B2'}, 'B': {'Type1': 'B1', 'Type2': 'B2'}}

    ====
    loop 2
    d: {'Type1': 'C1', 'Type2': 'C2'}
    D: {'A': {'Type1': 'C1', 'Type2': 'C2'}, 'B': {'Type1': 'C1', 'Type2': 'C2'}, 'C': {'Type1': 'C1', 'Type2': 'C2'}}

    ====


    from the output, the d is correct in every loop But D is getting changed in very loop! Not sure why it would be in that way.

    Continue reading...

Compartilhe esta Página