-1

I'm trying to get from a text file the dictionaries stored in a list

I searched for a json function, which can separate the string and save it in a list (a list of dictionaries), but I do not know if there is something like this.

txt:

[{"Principal": ["Jhon","Anderson","40"]}, {"Secretary": ["Marie","Garcia","29"]},{"Councilor": ["Alan", "Smith","33"]}]

py code:

stringvar=textfile.read()

// for or function below

dictionaries=json.loads(textfile.read())
otherlist=dictionaries
Georgy
  • 12,464
  • 7
  • 65
  • 73
gerardoicu
  • 39
  • 1
  • 5
  • I think I was specific, the txt file looks just like it in a single line, what I want to achieve is to save it in several dictionaries that I will later put in a list,thanks – gerardoicu Jan 13 '19 at 04:51
  • `dictionaries=json.loads(textfile.read())` already is a list of dictionaries. What do you miss? – mkiever Jan 13 '19 at 10:51

2 Answers2

0

First of all those kind of files are called json files.

You can open and read them as:

import json
f = open("results/results.json")
data = json.load(f)

Square brackets in json file defines an array, while curl brackets an object. The former will be converted to a list in python, the latter to dictionary.

So in your case data will be a list of dictionaries.

You can get the values and keys with the methods of the dictionary class keys(), values() or to get both items().

To be complete a the elements of your json should have the same structure, the fields only should change. For example considering one element:

{"role"    : "Principal",
 "name:    : "Jhon",
 "surname. : "Anderson",
 "age":   40}

In this way you can iterate more easily through your json

roschach
  • 8,390
  • 14
  • 74
  • 124
0

If you wish to load the list of dictionaries from a txt file in Python, you can do it using the literal_eval function from the ast module, in order to evaluate the expression of the string in the file:

import ast

data = []
with open("data.txt", "r") as inFile:
    data = ast.literal_eval(inFile.read())
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
  • What's wrong with `json.loads`? – mkiever Jan 18 '19 at 16:42
  • @mkiever `json.loads` should be the way of loading a dict from a file, as presented by Francesco Boi in the answer below. I just presented an alternative, thinking that the OP could not achieve the desired result using `json.load` as mentioned in the question. – Vasilis G. Jan 18 '19 at 17:47