简体   繁体   中英

Python how to read orderedDict from a txt file

Basically I want to read a string from a text file and store it as orderedDict. My file contains the following content.

content.txt:

variable_one=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']]))])

variable_two=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']]))])

how will I retrieve values in python as:

xxx 

   xxx_a -> xxx_b

   xxx_c -> xxx_d
import re
from ast import literal_eval
from collections import OrderedDict

# This string is slightly different from your sample which had an extra bracket
line = "variable_one=OrderedDict([('xxx', [['xxx_a', 'xxx_b'],['xx_c', 'xx_d']]),('yyy', [['yyy_a', 'yyy_b'],['yy_c', 'yy_d']])])"
match = re.match(r'(\w+)\s*=\s*OrderedDict\((.+)\)\s*$', line)
variable, data = match.groups()

# This allows safe evaluation: data can only be a basic data structure
data = literal_eval(data)

data = [(key, OrderedDict(val)) for key, val in data]
data = OrderedDict(data)

Verification that it works:

print variable
import json
print json.dumps(data, indent=4)

Output:

variable_one
{
    "xxx": {
        "xxx_a": "xxx_b", 
        "xx_c": "xx_d"
    }, 
    "yyy": {
        "yyy_a": "yyy_b", 
        "yy_c": "yy_d"
    }
}

Having said all that, your request is very odd. If you can control the source of the data, use a real serialisation format that supports order (so not JSON). Don't output Python code.

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