Home > Software design >  Create a nested dictionary from a txt file
Create a nested dictionary from a txt file

Time:04-18

Hi want to create a nested dictionary from a txt file.

The file looks this way:

BTC 5 42
ETH 0.2 1300

The expected result is this:

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

How can I do this? I can also change the structure of the txt file and/or use an xlsx file

CodePudding user response:

If your file contains:

BTC 5 42  
ETH 0.2 1300

then:

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)

creates crypto dictionary and prints:

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