Reputation: 11
When I run this code why are resultant two dictionaries not the same. I know it has something to do with how they are declared but as far as I can tell post deceleration but prior to assignment of values they are the same.
H=['DEPTH', 'CALI', 'S-SONIC', 'P-SONIC', 'GR', 'LITH', 'RESISTIVITY', 'NPHI', 'POROS', 'RHOB', 'SWARCH', 'SW_I', 'VP', 'VSH', 'VS']
Val=[]
Val.append(['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'])
Val.append(['16','17','18','19','20','21','22','23','24','25','26','27','28','29','30'])
Dict1={}
for name in H:
Dict1[name] = []
Dict2=dict.fromkeys(H,list())
for line in Val:
values = [float(val) for val in line]
for i, name in enumerate(H):
Dict1[name].append(values[i])
Dict2[name].append(values[i])
print 'DEPTH:', Dict1['DEPTH']
print 'DEPTH:', Dict2['DEPTH']
Thank you for any insight,
Dan
Upvotes: 1
Views: 50
Reputation: 4515
Your problem lies in dict.fromkeys(H, list())
. Only one list is being created, and it is being assigned to every key in the dictionary. Add a value to one key, and it gets added for all keys since they are all sharing one list.
You could use a dictionary comprehension instead to create Dict2
:
Dict2 = {key: [] for key in H}
Upvotes: 2