使用文件更新词典

时间:2017-11-21 20:24:33

标签: python dictionary

我有以下文件,我需要更新两个词典。其中一个映射人员朋友,另一个映射人员网络。该文件采用以下格式:     普里切特,杰伊     普里切特,格洛丽亚     德尔加多,曼尼     Dunphy,Claire

Dunphy, Claire
Parent Teacher Association
Dunphy, Phil
Pritchett, Mitchell
Pritchett, Jay

Scrooge, McDuck

Delgado, Manny
Chess Club
Pritchett, Gloria
Pritchett, Jay
Dunphy, Luke

Pritchett, Mitchell
Law Association
Dunphy, Claire
Tucker, Cameron
Dunphy, Luke

Dunphy, Alex
Orchestra
Chess Club
Dunphy, Luke

Tucker, Cameron
Clown School
Wizard of Oz Fan Club
Pritchett, Mitchell
Pritchett, Gloria

Dunphy, Haley Gwendolyn
D-Money, Dylan
D-Cat, Gilbert

Dunphy, Phil
Real Estate Association
Dunphy, Claire
Dunphy, Luke

D-Money, Dylan
D-Cat, Chairman

Dunphy, Haley Gwendolyn

Pritchett, Gloria
Parent Teacher Association
Pritchett, Jay 
Tucker, Cameron
Delgado, Manny

Dunphy, Luke
Delgado, Manny
Dunphy, Alex
Dunphy, Phil
Pritchett, Mitchell

我使用readline()方法读取文件并相应地更新字典。仅供参考,字典看起来像这样:

person_to_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria 
Pritchett', 'Manny Delgado']...

person_to_networks = {'Claire Dunphy': ['Parent Teacher Association'], 
'Manny Delgado': ['Chess Club']...

到目前为止,我有这个代码,我试图读取文件,但我遇到了麻烦,因为它不是将第一个名称作为密钥,而是使每个名称直到换行符为止。

friends = []
line = profiles_file.readline()
while line != '':
    profiles = format_name(line)
    if not profiles in person_to_friends:
        person_to_friends[profiles] = []
    line = profiles_file.readline()
    if not ',' in line:
        network = line
        line = profiles_file.readline()
    else:
        if format_name(line) != '' and format_name(line) not in person_to_friends[profiles]:
            person_to_friends[profiles].append(format_name(line))
            line = profiles_file.readline()


return person_to_friends

对于参考,format_name只是我编写的一个函数,用于确保文件中的名称格式为'名字姓氏'并删除换行符。

0 个答案:

没有答案