简体   繁体   中英

Python Dictionary Stored as String in List

I have a txt file that contains a dictionary in Python and I have opened it in the following manner:

with open('file') as f:
    test = list(f)

The result when I look at test is a list of one element. This first element is a string of the dictionary (which also contains other dictionaries), so it looks like:

["ID": 1, date: "2016-01-01", "A": {name: "Steve", id: "534", players:{last: "Smith", first: "Joe", job: "IT"}}

Is there any way to store this as the dictionary without having to find a way to determine the indices of the characters where the different keys and corresponding values begin/end? Or is it possible to read in the file in a way that recognizes the data as a dictionary?

If you are reading a json file then you can use the json module.

import json

with open('data.json') as f:    
    data = json.load(f)

If you are sure that the file you are reading contains python dictionaries, then you can use the built-in ast.literal_eval to convert those strings to a Python dictionary:

>>> import ast
>>> a = ast.literal_eval("{'a' : '1', 'b' : '2'}")
>>> a
{'a': '1', 'b': '2'}
>>> type(a)
<type 'dict'>

There is an alternative method, eval . But using ast.literal_eval would be better. This answer will explain why.

You can use json module

for Writing

import json

data = ["ID": 1, date: "2016-01-01", "A": {name: "Steve", id: "534", players:{last: "Smith", first: "Joe", job: "IT"}}
with open("out.json", "w") as f:
    json.dump(data)

for Reading

import json

with open("out.json", "w") as f:
    data = json.load(f)
    print data

Just use eval() when you read it from your file.

for example:

>>> f = open('file.txt', 'r').read()
>>> mydict = eval(f)
>>> type(f)
<class 'str'>
>>> type(mydict)
<class 'dict'>

The Python interpreter thinks you are just trying to read an external file as text. It does not know that your file contains formatted content. One way to import easily as a dictionary be to write a second python file that contains the dictionary:

# mydict.py
myImportedDict = {
    "ID": 1, 
    "date": "2016-01-01", 
    "A": {
        "name": "Steve", 
        "id": "534", 
        "players": {
            "last": "Smith", 
            "first": "Joe", 
            "job": "IT"
        }
    }
}

Then, you can import the dictionary and use it in another file:

#import_test.py
from mydict import myImportedDict

print(type(myImportedDict))
print(myImportedDict)

Python also requires that folders containing imported files also contain a file called

__init__.py

which can be blank. So, create a blank file with that name in addition to the two files above.

If your source file is meant to be in JSON format, you can use the json library instead, which comes packaged with Python: https://docs.python.org/2/library/json.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM