[Tutor] Building dictionary from large txt file

bobx ander bobxander87 at gmail.com
Tue Jul 26 16:58:06 EDT 2022


Hi all,
I'm trying to build a dictionary from a rather large file of following
format after it has being read into a list(excerpt from start of list below)
--------

Atomic Number = 1
    Atomic Symbol = H
    Mass Number = 1
    Relative Atomic Mass = 1.00782503223(9)
    Isotopic Composition = 0.999885(70)
    Standard Atomic Weight = [1.00784,1.00811]
    Notes = m
--------

My goal is to extract the content into a dictionary that displays each
unique triplet as indicated below
{'H1': {'Z': 1,'A': 1,'m': 1.00782503223},
              'D2': {'Z': 1,'A': 2,'m': 2.01410177812}
               ...} etc
My code that I have attempted is as follows:

filename='ex.txt'

afile=open(filename,'r') #opens the file
content=afile.readlines()
afile.close()
isotope_data={'Z':0,'A':0,'m':0}#start to create subdictionary for
each case of atoms with its unique keys and values
for line in content:
    data=line.strip().split()

    if len(data)<1:
        pass
    elif data[0]=="Atomic" and data[1]=="Number":
        atomic_number=data[3]


     elif data[0]=="Mass" and data[1]=="Number":
        mass_number=data[3]



    elif data[0]=="Relative" and data[1]=="Atomic" and data[2]=="Mass":
        relative_atomic_mass=data[4]


isotope_data['Z']=atomic_number
isotope_data['A']=mass_number
isotope_data['A']=relative_atomic_mass
isotope_data

the output from the programme is only

{'Z': '118', 'A': '295', 'm': '295.21624(69#)'}

I seem to be owerwriting each dictionary and ends up with the above
result.Somehow i think I have to put
the assigment of the key,value pairs elsewhere.

I have tried directly below the elif statements also,but that did not work.

Any hints or ideas

Regards

Bob


More information about the Tutor mailing list