[Tutor] problem with dictionaries
Kent Johnson
kent_johnson at skillsoft.com
Mon Aug 23 22:26:12 CEST 2004
You just have to get the dictionary and assign the new key:
>>>
d={'position1':{'A1':'N1','A2':'N2','A3':'N3','Ax':'Nx'},'position2':{'B1':'M1','B2':'M2','Bx':
'Mx'}}
>>> p1=d['position1']
>>> p1
{'A1': 'N1', 'Ax': 'Nx', 'A3': 'N3', 'A2': 'N2'}
p1 and d['position1'] both refer to the same dictionary, so adding to p1
also changes d:
>>> p1['Ay'] = 'Ny'
>>> p1
{'A1': 'N1', 'Ax': 'Nx', 'A3': 'N3', 'A2': 'N2', 'Ay': 'Ny'}
>>> d
{'position2': {'Bx': 'Mx', 'B1': 'M1', 'B2': 'M2'}, 'position1': {'A1':
'N1', 'Ax': 'Nx', 'A3': 'N3', 'A2': 'N2', 'Ay': 'Ny'}}
You can do it all in one line:
>>> d['position1']['Az'] = 'Nz'
>>> d
{'position2': {'Bx': 'Mx', 'B1': 'M1', 'B2': 'M2'}, 'position1': {'A1':
'N1', 'A3': 'N3', 'A2': 'N2', 'Ay': 'Ny', 'Ax': 'Nx', 'Az': 'Nz'}}
If you're not sure if the dictionary is there yet use setdefault on d, this
will make a new entry if needed (instead of throwing a KeyError):
>>> d.setdefault('position3', {})['C1'] = 'P1'
>>> d
{'position2': {'Bx': 'Mx', 'B1': 'M1', 'B2': 'M2'}, 'position3': {'C1':
'P1'}, 'position1': {'A1': 'N1', 'A3': 'N3', 'A2': 'N2', 'Ay': 'Ny', 'Ax': 'Nx
', 'Az': 'Nz'}}
Kent
At 01:08 PM 8/23/2004 -0700, Christian Meesters wrote:
>Hi
>
>Thanks again for the last time I asked for help. I solved the problem
>combining the input of Alan and Kent. Your help was really valuable!
>
>But now I have a more basic problem:
>Imagine your want to nest dictionaries like this:
>{position1:{A1:N1,A2:N2,A3:N3,...,Ax:Nx},position2:{B1:M1,B2:M2,...,Bx:
>Mx},...}
>
>How do you add an Ay:Ny pair at position1 without overriding the
>already present dictionary there? (I vaguely remember this, but cannot
>find it anywhere in the documentations. Pointing me on an example is
>probably sufficient ;-) .)
>
>Thanks a lot,
>Christian
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list