从 txt 文件创建嵌套字典

Create a nested dictionary from a txt file

您好,想从 txt 文件创建嵌套字典。

文件看起来是这样的:

BTC 5 42
ETH 0.2 1300

预期结果是这样的:

crypto = {
    "c1" :
        {
            "name" : "BTC",
            "amount" : "5",
            "avalue" : "42000" 
        } ,
    "c2" :
        {
            "name" : "ETH",
            "amount" : "0.2",
            "avalue" : "2000" 
    }

我该怎么做?我还可以更改 txt 文件的结构 and/or 使用 xlsx 文件

如果您的文件包含:

BTC 5 42  
ETH 0.2 1300

然后:

crypto = {}
with open("your_file.txt", "r") as f_in:
    i = 1
    for line in map(str.strip, f_in):
        if line == "":
            continue
        name, amount, avalue = line.split()
        crypto[f"c{i}"] = {"name": name, "amount": amount, "avalue": avalue}
        i += 1

print(crypto)

创建 crypto 字典并打印:

{
    "c1": {"name": "BTC", "amount": "5", "avalue": "42"},
    "c2": {"name": "ETH", "amount": "0.2", "avalue": "1300"},
}