Reputation: 13
I have this code:
def create_dict(my_file):
my_lines = my_file.readlines()
my_dict = {}
for line in my_lines:
items = line.split()
key, values = items[0], items[2:3] + items[1:2] + items[5:6] +items[3:4] + items[4:5]
my_dict[key] = values
return my_dict
I need it to return
{
'asmith': ['Smith', 'Alice', '[email protected]', 31, 'F'],
'rford': ['Ford', 'Rob', '[email protected]', 44, 'M']
}
But its returning:
{
'asmith': ['Smith', 'Alice', '[email protected]', '31', 'F'],
'rford': ['Ford', 'Rob', '[email protected]', '44', 'M'].
}
I need to change the age values into integers and i've tried using int(items[3:4])
, but it says that the object has to be a string to be converted into an integer. Can anyone seem to find out why its doing this?
Upvotes: 0
Views: 74
Reputation: 2253
say your my_file
has two lines like following:
asmith Smith Alice [email protected] 31 F
rford Ford Rob [email protected] 44 M
and you can use this:
def create_dict(my_file):
my_dict = {}
with open(my_file, 'r') as f: # close file without do it by yourself
for line in f: # it works even though the file has large size
items = line.split()
items[4] = int(items[4]) # convert age type from str to int
my_dict[items[0]] = items[1:]
return my_dict
test:
>>> create_dict('/home/mingxian/Desktop/pythontest/testfile')
{'rford': ['Ford', 'Rob', '[email protected]', 44, 'M'], 'asmith': ['Smith', 'Alice', '[email protected]', 31, 'F']}
Upvotes: 0
Reputation: 690
Should be int(my_dict['asmith'][3])
items[3:4]
returns a list which cannot be turned into an integer. items[3]
appears to be the location of age.
Upvotes: 0