# How to parse a text file into a nested dictionary and save it

**URL:** <https://discuss.python.org/t/how-to-parse-a-text-file-into-a-nested-dictionary-and-save-it/12389>\
**Category:** Python Help\
**Tags:** help\
**Created:** [December 7, 2021, 7:05am UTC](https://discuss.python.org/t/how-to-parse-a-text-file-into-a-nested-dictionary-and-save-it/12389 "2021-12-07T07:05:34Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![CAM-Gerlach](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/cam-gerlach/32/3688_2.png) [@CAM-Gerlach](https://discuss.python.org/u/CAM-Gerlach)\
**Post date:** [December 7, 2021, 11:41pm UTC](https://discuss.python.org/t/how-to-parse-a-text-file-into-a-nested-dictionary-and-save-it/12389/4 "2021-12-07T23:41:53Z")

</div>

In addition to the comments above, you might want to consider the popular [Pandas](https://pandas.pydata.org/) library, which makes working with tabular data much easier. You can read your CSV file into a Pandas DataFrame in one line, `df = pandas.read_csv(database_filename, names=['quantity', 'fee', 'powers'], index_col=0)`, and it will automatically convert all the data types for you. You can then output it to a Python dict in the specified format with `df.to_dict(orient='index')`, to a JSON file with `df.to_json(json_filename, orient='index')` or to your original CSV with `df.to_csv(database_filename)`. You can sort your df with `df.sort_index()`

However, there is one potential problem with either this approach or the previous suggested `csv` based one—you have a variable number of `powers` fields, which it looks like you intend to read as a nested list. Bringing in a bit of domain-specific knowledge, it looks like this corresponds to a Pokemon’s “Type”, which per [Bulbapedia](https://bulbapedia.bulbagarden.net/wiki/Type), a Pokemon can only have one or two types. Thus, the simplest way to handle this is to just declare two columns, `type1` and `type2`, and Pandas (or `csv`) will fill in the second one with a full value if it is not present. Of course, that doesn’t get you a list in your output data structure, but is a lot simpler to work with; once you get your dict, you can concatenate them into a list, e.g. something like `data_dict['types'] = [data_dict.pop(f'type{n}') for n in [1, 2] if f'type{n}' in data_dict]`.

---

_[View the full topic](https://discuss.python.org/t/how-to-parse-a-text-file-into-a-nested-dictionary-and-save-it/12389)._
