I have a text file containing dictionaries, one per line, of user information:
{'username': 'jsmith', 'fullname': 'John Smith', 'email': '[email protected]'}
{'username': 'ajones', 'fullname': 'Betty Jones', 'email': '[email protected]'}
{'username': 'pmills', 'fullname': 'Paul Mills', 'email': '[email protected]'}
My python script needs to iterate thru this file and assign each value in each dictionary to a variable. The script looks like this:
import subprocess
import ast
# iterate through users file line by line
with open('users.txt') as users:
for line in users:
d_line = ast.literal_eval(line)
for k,v in d_line.items():
un = v['username']
full = v['fullname']
mail = v['email']
print (un, full, mail)
But I get this error:
Traceback (most recent call last):
File "admin-add.py", line 13, in <module>
un = v['username']
TypeError: string indices must be integers
Not sure why it is still treating the line as a string.
CodePudding user response:
The problem is that you are iterating through the items in d_line
and assigning v
to the value of each item. However, v
is not a dictionary, it is the value of the key-value pair in d_line
, which is a string.
Instead, you should iterate through the key-value pairs in d_line
and assign k
to the key and v
to the value, like this:
import ast
# iterate through users file line by line
with open('users.txt') as users:
for line in users:
d_line = ast.literal_eval(line)
for k, v in d_line.items():
if k == 'username':
un = v
elif k == 'fullname':
full = v
elif k == 'email':
mail = v
print(un, full, mail)
CodePudding user response:
It just needs to iterate each line in file and evaluate it as dictionaries then get the value of each keys
from ast import literal_eval
with open('users.txt') as users:
for line in users:
d_line = literal_eval(line)
un, full, mail = d_line['username'], d_line['fullname'], d_line['email']
print(un, full, mail)