開いているファイルを唯一のパラメーターとして取り、文字列を文字列と整数のリストにマップする辞書を返す関数を作成する必要があります。
テキストの各行には、ユーザー名、名、姓、年齢、性別、電子メール アドレスが含まれます。この関数は、ユーザー名をキーとして各人の情報を辞書に挿入し、値は [姓、名、電子メール、年齢、性別] のリストです。
基本的に私がやろうとしているのは、これを含むテキストファイルを開くことです:
ajones Alice Jones 44 F alice@alicejones.net
次のようなものを返します。
{ajones: ['Jones', 'Alice', 'alice@alicejones.net', 44, 'F']}
ここまでできたのですが、他にもっと簡単な方法はありませんか?
def create_dict(file_name):
'''(io.TextIOWrapper) -> dict of {str: [str, str, str, int, str]}
'''
newdict = {}
list2 = []
for line in file_name:
while line:
list1 = line.split() #for a key, create a list of values
if list2(0):
value += list1(1)
if list2(1):
value += list1(2)
if list2(2):
value += list1(3)
if list2(3):
value += list1(4)
newdict[list1(0)] = list2
for next_line in file_name:
list1 = line.split()
newdict[list1(0)] = list1
return newdict
def helper_func(fieldname):
'''(str) -> int
Returns the index of the field in the value list in the dictionary
>>> helper_func(age)
3
'''
if fieldname is "lastname":
return 0
elif fieldname is "firstname":
return 1
elif fieldname is "email":
return 2
elif fieldname is "age":
return 3
elif fieldname is "gender":
return 4