Adarsh H D Dev Adarsh H D Dev - 4 days ago 5
Python Question

Not able add the second line to dictionary in Python

I am new to Python scripting. There is a file which contains data below

Cascade.from= testvalue1
cascade.from1=testvalue2


The above context is in test.txt. I have written a below code in order to put this in dictionary and fetch it later code is as below

myvalue = {}
with open('test.txt', 'r') as myfile:
for line in myfile:
name, val = line.split('=')
myvalue[name] = str(val.strip())
print myvalue`


after running the above code, i see only below data
{"cascade.from":"testvalue1"}

its not reading the next line and its not getting added to the dictionary.
My expection is
{"cascade.from":"testvalue1","cascade.from1":"testvalue2"}
So that when call
myvalue["cascade.from1"]
it should retrun be
testvalue2

Could anyone let me know what am missing here?

The above was just a small piece inside a function, here is my code complete thing

def readlocalfile():
os.chdir(sub_dir)
print ("prinintng current directory" + os.getcwd())
file=open(config_file,'r')
file_read=file.readlines()
myvars = {}
with open(config_file) as myfile:
for line in myfile:
name, var = line.split("=")
myvars[name] = str(var.strip())
print myvars
replace_val= myvars["cascade.from1"]
print ("the base value is "+ replace_val)


Am calling this function outside. which throws a KeyError

Answer

The first time in the loop, you are trying to read

myvars["cascade.from1"]

But the key cascade.from1 does not exists in the first time in the loop, since you only have loaded the first line which is Cascade.from (the key cascade.from1 is created the second time in the loop) And thats why you get an error and your program craches at the row replace_val= myvars["cascade.from1"] the first time. Therefore print myvars is only run the first time in the loop, when you only have read the first line in the file.

To use

replace_val= myvars["cascade.from1"]

You have to move it outside the loop since ince myvars does not contain the key cascade.from1 inside the loop the first time:

def readlocalfile():
    os.chdir(sub_dir)
    print ("prinintng current directory" + os.getcwd())
    file=open(config_file,'r')
    file_read=file.readlines()
    myvars = {}
    with open(config_file) as myfile:
        for line in myfile:
            name, var = line.split("=")
            myvars[name] = str(var.strip())
            print myvars
        replace_val= myvars["cascade.from1"]
        print ("the base value is "+ replace_val)
Comments