rmstmg rmstmg - 3 months ago 7
Python Question

How to pass dictionary to functions?

I want to pass dictionary to user defined functions and I need to do some calculation based on the dictionary values. It is not working for me with functions but works fine without using functions. I am not sure, what is wrong with code. Any help please? No error message.

Input:


"13-07-2016 12:55:46",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 12:57:50",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:00:43",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:01:45",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:02:57",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:04:59",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:06:51",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"

"13-07-2016 13:07:56",user,192.168.10.100,192.168.10.20,CONNECT,200,"www.abc.com"


Code:

file_name = sys.argv[1]
fo = open(file_name, "rb")


def setdict():
dico,i={},0

line = fo.readline()
for line in fo:
date, user, proxy_ip, client_ip, access_method, con, sites = line.split(",")
sites = sites.rstrip('\n')
dico[i]= date, user, proxy_ip, client_ip, access_method, con, sites
return dico

def display(dico):
for k,v in dico.items():
print k,v

Answer

You should consider to call your functions :

file_name = sys.argv[1]
fo = open(file_name, "rb")


def setdict():
   dico,i={},0

   line = fo.readline()
   for line in fo:
     date, user, proxy_ip, client_ip, access_method, con, sites = line.split(",")
     sites = sites.rstrip('\n')
     dico[i]= date, user, proxy_ip, client_ip, access_method, con, sites
   return dico

def display(dico):
   for k,v in dico.items():
      print k,v

dico = setdict()
display(dico)

You should also consider a better way to open your file:

with open(file_name, "rb") as f:
  lines = f.readlines()
  for line in lines:
    ...

Finally, you use :

   line = fo.readline()
   for line in fo:
     #do stuff on line

Do you know that the first line of your file will not be in your dict ?