Thank you very much.
import collections
def main():
dict1 = collections.OrderedDict()
dict2 = collections.OrderedDict()
dict3 = collections.OrderedDict()
dict1['A'] = 0
dict1['B'] = 0
dict1['C'] = 0
for c in [1, 2, 3]:
print('c=' + str(c))
dict2 = dict1
print('dict1A=' + str(dict1['A']))
print('dict2A=' + str(dict2['A']))
if c == 1:
dict2['A'] = 1
dict2['B'] = 2
dict2['C'] = 3
elif c ==2:
dict2['A'] = 4
dict2['B'] = 5
dict2['C'] = 6
elif c ==3:
dict2['A'] = 7
dict2['B'] = 8
dict2['C'] = 9
dict3['c' + str(c)] = dict2
print('dict2A=' + str(dict2['A']))
print('dict' + str(c) + 'A=' + str(dict3['c' + str(c)]['A']))
print('dict' + str(c) + 'B=' + str(dict3['c' + str(c)]['B']))
print('dict' + str(c) + 'C=' + str(dict3['c' + str(c)]['C']))
print('dict3-c1A='+ str(dict3['c1']['A']))
print('dict3-c2B=' + str(dict3['c2']['B']))
print('dict3-c3C=' + str(dict3['c3']['C']))
if __name__ == '__main__':
main()
Output:
c=1
dict1A=0
dict2A=0
dict2A=1
dict1A=1
dict1B=2
dict1C=3
c=2
dict1A=1
dict2A=1
dict2A=4
dict2A=4
dict2B=5
dict2C=6
c=3
dict1A=4
dict2A=4
dict2A=7
dict3A=7
dict3B=8
dict3C=9
dict3-c1A=7
dict3-c2B=8
dict3-c3C=9
* EDIT * Thank you very much for the answers. I didn't know the '=' operation for dictionaries was not the same as for variables. I found out and as was suggested by g.d.d.c, that the copy() is what I wanted:
dict2 = dict1.copy()
When you assign dict2 = dict1
you replace the name which previously existed as an empty OrderedDict
and tell the interpreter instead to use dict2
to refer to the same Object
that exists in the name dict1
. You can do a couple of things to work around this:
# copy
dict2 = dict1.copy()
# update dict 2
dict2.update(dict1.iteritems())
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments