使用Python 3从文本文件创建嵌套字典

时间:2019-06-22 07:03:55

标签: python dictionary

这是我的文件: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'}}

3 个答案:

答案 0 :(得分:2)

在给定数据格式不变的情况下,如何在不导入csv的情况下执行此操作:

fixed = {}
i = 1
with open("test.txt", 'r') as f:
    for line in f:
        listDetails = line.strip().split('|')
        fixed[i] = {"Name": listDetails[0]}
        fixed[i].update({"Sex": listDetails[1]})
        fixed[i].update({"Description": listDetails[2]})
        fixed[i].update({"Age": listDetails[3]})
        i+=1
print(fixed)

这应该变成

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

收件人

{1: {'Name': 'Amy', 'Sex': 'Female', 'Description': 'Desc1', 'Age': '12'}, 2: {'Name': 'John', 'Sex': 'Male', 'Description': 'Desc2', 'Age': '10'}, 3: {'Name': 'Mike', 'Sex': 'Male', 'Description': 'Desc3', 'Age': '18'}}

编辑:就像Nakor所说的那样,在这里做出命令是没有意义的,如果确实需要将其发布为命令,则将其发布。

答案 1 :(得分:1)

您想要的输出看起来更像是字典列表。 在这种情况下,我将像这样修改您的代码:

@{push}

输出:

import csv
with open('test.txt') as file:
    tsvfile = csv.reader(file, delimiter='|')
    d = []

    for row in tsvfile:
        entry = {
          'Name': row[0],
          'Gender': row[1],
          'Desc': row[2],
        }
        d.append(entry)
    print(d)

您甚至可以像这样更紧凑地编写循环:

[{'Name': 'Amy', 'Gender': 'Female', 'Desc': 'Desc1'}, 
 {'Name': 'John', 'Gender': 'Male', 'Desc': 'Desc2'}, 
 {'Name': 'Mike', 'Gender': 'Male', 'Desc': 'Desc3'}]

编辑:如果您要以行号作为键的字典,则可以执行以下操作:

keys = ["Name","Gender","Desc"]
for row in tsvfile:
    entry = { key: value for (key,value) in zip(keys,row) }
    d.append(entry)

答案 2 :(得分:1)

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)