这是我的文件:test.txt

Amy|Female|Desc1|12
John|Male|Desc2|10
Mike|Male|Desc3|18

我试图创建嵌套字典,但没有成功。
这是输出:
{'Amy': '12', 'John': '10', 'Mike': '18'}

这是我的代码:
import csv
with open('test.txt') as file:
    tsvfile = csv.reader(file, delimiter='|')
    d = {}

    for row in tsvfile:
        d[row[0]] = row[0] #this should be name
        d[row[0]] = row[1] #this should be gender
        d[row[0]] = row[3] #this should be desc
        d[row[0]] = row[3] #this should be age
    print(d)

我的期望输出如下,但没有成功。
d={1{'Name':'Amy', 'Gender':'Female', 'Desc': 'Desc1', 'Age': '12'}
 2{'Name':'John', 'Gender':'Male', 'Desc': 'Desc2', 'Age': '10'}
 3{'Name':'Mike', 'Gender':'Male', 'Desc': 'Desc3', 'Age': '18'}}

及以下(仅限姓名和年龄
d1={1{'Name':'Amy','Age': '12'}
 2{'Name':'John', 'Age': '10'}
 3{'Name':'Mike', 'Age': '18'}}

最佳答案

1)嵌套字典,我在同一个代码中做了一些修改,可能对你有帮助。

import csv
with open('hello.txt') as file:
tsvfile = csv.reader(file, delimiter='|')
final_dict = {}
counter = 1
for row in tsvfile:
    d = {}
    d['Name'] = row[0] #this should be name
    d['Gender'] = row[1] #this should be gender
    d['Desc'] = row[2] #this should be desc
    d['Age'] = row[3] #this should be age
    final_dict[counter] = d
    counter+=1
print(final_dict)

关于python - 使用Python 3从文本文件创建嵌套字典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56713360/

10-12 22:07