-2

I have this txt file but I'm having trouble in converting it into a nested dictionary in python. The txt file only has the values of the pokemon but are missing the keys such as 'quantity' or 'fee'. Below is the content in the txt file. (I have the ability to change the txt file if needed)

pokemon info

charmander,3,100,fire
squirtle,2,50,water
bulbasaur,5,25,grass
gyrados,1,1000,water flying

This is my desired dictionary:

pokemon = {
         'charmander':{'quantity':3,'fee':100,'powers':['fire']},
         'squirtle':{'quantity':2,'fee':50,'powers':['water']},
         'bulbasaur':{'quantity':5,'fee':25,'powers':['grass']},
         'gyrados':{'quantity':1,'fee':1000,'powers':['water','flying']}
      }
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

Convert text file to lines, then process each line using "," delimiters. For powers, split the string again using " " delimiter. Then just package each extracted piece of information into your dict structure as below.

with open('pokemonInfo.txt') as f:
    data = f.readlines()

dict = {}
for r in data:
    fields = r.split(",")
    pName = fields[0]
    qty = fields[1]
    fee = fields[2]
    powers = fields[3]

    dict[pName] = {"quantity": qty, "fee": fee, "powers": [p.strip() for p in powers.split(" ")]}

for record in dict.items():
    print(record)
Eric
  • 504
  • 4
  • 4
  • thank you so much that worked perfectly, you literally saved my day. Just a quick question... I'm confused with the use of strip() for separating the powers, would you mind explaining that? Thanks – Max Chi Dec 05 '21 at 21:57
  • strip() is a method on python strings that removes white space from either side of the string it is run against. This includes spaces, newline characters, tabs, etc. Since the powers are likely going to be used in your program down the road, running strip() on each one when you enter them in your initial data structure makes using them more predictable down the road. – Eric Dec 05 '21 at 22:06
  • Don't use `dict` as a variable name, as it shadows the `dict` type. – Gino Mempin Dec 05 '21 at 23:21