Ricky18
Ricky18

Reputation: 45

How to create/read nested dictionary from file?

Here is the text file1 content

name = test1,description=None,releaseDate="2020-02-27"
name = test2,description=None,releaseDate="2020-02-28"
name = test3,description=None,releaseDate="2020-02-29"

I want a nested dictionary like this. How to create this?

{ 'test1': {'description':'None','releaseDate':'2020-02-27'},
  'test2': {'description':'None','releaseDate':'2020-02-28'},
  'test3': {'description':'None','releaseDate':'2020-02-29'}}

After this I want to append these values in the following line of code through "for" loop for a list of projects.

Example: For a project="IJTP2" want to go through each name in the dictionary like below

project.create(name="test1", project="IJTP2", description=None, releaseDate="2020-02-27")
project.create(name="test2", project="IJTP2", description=None, releaseDate="2020-02-28")
project.create(name="test3", project="IJTP2", description=None, releaseDate="2020-02-29")

Now to the next project:

List of projects is stored in another file as below

IJTP1
IJTP2
IJTP3
IJTP4

I just started working on Python and have never worked on the nested dictionaries.

Upvotes: 0

Views: 179

Answers (1)

Boseong Choi
Boseong Choi

Reputation: 2596

I assume that:

  • each file line has comma-separated columns
  • each column has only one = and key on its left, value on its right
  • only first column is special(name)

Of course, as @Alex Hall mentioned, I recommend JSON or CSV, too.
Anyway, I wrote code for your case.

d = {}
with open('test-200229.txt') as f:
    for line in f:
        (_, name), *rest = (
            tuple(value.strip() for value in column.split('='))
            for column in line.split(',')
        )
        d[name] = dict(rest)

print(d)

output:

{'test1': {'description': 'None', 'releaseDate': '"2020-02-27"'}, 'test2': {'description': 'None', 'releaseDate': '"2020-02-28"'}, 'test3': {'description': 'None', 'releaseDate': '"2020-02-29"'}}

Upvotes: 1

Related Questions