I'm trying to create a dictionary and my dictionary keys keep overwriting themselves. I don't understand how I can handle this issue.
Here's the script:
import MDAnalysis as mda
u = mda.Universe('rps5.prmtop', 'rps5.inpcrd')
ca = u.select_atoms('protein')
charges = ca.charges
atom_types = ca.names
resnames = ca.resnames
charge_dict = {}
for i in range(len(charges)):
#print(i 1 ,resnames[i], atom_types[i], charges[i])
charge_dict[resnames[i]] = {}
charge_dict[resnames[i]][atom_types[i]] = charges[i]
print(charge_dict)
The charges, atom_types and resnames are all lists, with the same number of elements.
I want my dictionary to look like this: charge_dict[resname][atom_types] = charges (charge_dict['MET']['CA'] = 0.32198, for example).
Could you please help me with this issue?
CodePudding user response:
Without actually seeing a complete problem description, my guess is that your final result is that each charge_dict[name]
is a dictionary with just one key. That's not because the keys "overwrite themselves". Your program overwrites them explicitly: charge_dict[resnames[i]] = {}
.
What you want is to only reset the value for that key if it is not already set. You could easily do that by first testing if resnames[i] not in charge_dict:
, but the Python standard library provides an even simpler mechanism: collections.defaultdict
. A defaultdict
is a dictionary with an associated default value creator. So you can do the following:
from collections import defaultdict
charge_dict = defaultdict(dict)
After that, you won't need to worry about initializing charge_dict[name]
because a new dictionary will automatically spring into existence when the default value function (dict
) is called.