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

标签 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'}}

最佳答案

假设数据格式不变,以下是如何在不导入 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 所说,在这里制作字典的字典实际上没有意义,如果您确实需要将其设为字典,只需发布​​此内容。

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

相关文章:

vb.net - 是否可以使用字符串键/值对初始化New System.Collections.Generic.Dictionary?

c - Stdin + 字典文本替换工具 -- 调试

python - 位置参数和 self 关键字

python - 在 QMainWindow __init__() 上发出请求,不延迟打开

python - 如何在 flask 脚本的@manager.options 中设置默认值

python - 字典未引用的字符串?

python - 按元组的指定元素对带有元组键的字典进行排序

python - 将模拟树的字典转换为列表

python - Flask Social - FACEBOOK_SOCIAL 不接受 request_token_params 参数

python - 如何以自定义方式呈现 CheckboxGroup(或任何其他元素)?