Cheng Zheng
Cheng Zheng

Reputation: 31

How to read text file to convert to dictionary?

I'm trying to read a text file contains dictionaries separated by comma, and convert to a list of dictionaries.

How can I do this with python?

I tried to read as json file or use split method

{
    "id": "b1",
    "name": "Some Name" 
},
{
    "id": "b2",
    "name": "Another Name"
},
....

result should be:

[ {"id" : "b1", "name" : "Some Name"} , {"id" : "b2", "name" : "Another Name"}, .... ]

Upvotes: 1

Views: 1354

Answers (3)

Sagar
Sagar

Reputation: 404

Welcome to Stack Overflow..!

If you are using a JSON file to store data, then I highly recommend the Python JSON Library. How to use it you ask..? Read this

If you plan on using a Text file to store data, I recommend that you store the data a bit differently than the JSON format

b1,Some Name
b2,Another Name
.
.

This would make reading the text file way easier. Just use the split() command to separate the lines from one another and then use split(",") on each of the lines to separate the ID from the Name.

Here is the code:

list = open("filename.txt").read().split("\n")
dictionaryList = []
for item in list:
    id, name = item.split(",")
    dictionaryList.append({id:name})

Hope this works..! SDA

Upvotes: 0

rohit prakash
rohit prakash

Reputation: 575

You can use json module in python

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript).

json exposes an API familiar to users of the standard library marshal and pickle modules. https://docs.python.org/2/library/json.html

In your case if your file is a valid json file then you can use json.loads() method directly

import json

with open('test.txt', 'r') as file:
    result = json.loads(file.read())

Upvotes: 0

iz_
iz_

Reputation: 16633

If your file is not too big, you can do the following:

import json

with open('filename.txt', 'r') as file:
    result = json.loads('[' + file.read() + ']')

Upvotes: 2

Related Questions