简体   繁体   English

Python:文本文件到字典,同时保留顺序?

[英]Python: Text file to dictionary whilst preserving order?

I have a text file with contents such as: 我有一个文本文件,其内容如下:

{'InventoryTake':'Key','OtherSceneNode':'Shed','AddOtherScene':'ShedOpen'}

And the code that retrieves the data from the text file: 以及从文本文件中检索数据的代码:

    readin = eventVar.readline()
    Results = eval(readin)

The problem I'm having is that I need to keep my dictionary in order due to the nature of the code it runs. 我遇到的问题是,由于运行代码的性质,我需要保持字典顺序。 However python stores dictionary keys in random order. 但是python以随机顺序存储字典键。

I have tried using an ordered Dictionary to preserve the order, but this doesn't make a difference. 我已经尝试使用有序的字典来保存订单,但这没有什么区别。 I think this is because by the time the ordered dictionary gets a hold of the information, it has already been sorted by whatever is reading it in from the file. 我认为这是因为当有序字典获取信息时,它已经按照从文件中读取的任何内容进行排序。

I have tried eval, literal_eval and a json parser to read the data in correctly, but the dictionary always comes out in the wrong order when running the program. 我已经尝试使用eval,literal_eval和json解析器来正确读取数据,但是在运行程序时字典总是以错误的顺序出现。

The aim of this part of the program is to allow the text file dictionary to store as many of those pairs as possible (OtherSceneNode and AddOtherScene / TakeOtherScene). 该部分程序的目的是允许文本文件字典尽可能多地存储这些对(OtherSceneNode和AddOtherScene / TakeOtherScene)。 So I can't assume there is only one set of those key value pairs. 所以我不能假设这些键值对中只有一组。

I'm using python 2.7.5, and if it helps the order its coming out in is: 我正在使用python 2.7.5,如果它有助于它出现的顺序是:

{'InventoryTake':'Key','AddOtherScene':'ShedOpen','OtherSceneNode':'Shed'}

I could redo the text files to take specific lines, but that will make my text files even more complicated and I feel its just avoiding a problem rather than solving one. 我可以重做文本文件以获取特定的行,但这将使我的文本文件更加复杂,我觉得它只是避免问题而不是解决问题。

One method would be to look up the parsed data pairs in the string to find their original relative order: 一种方法是在字符串中查找已解析的数据对以查找其原始相对顺序:

line = "{'InventoryTake':'Key','OtherSceneNode':'Shed','AddOtherScene':'ShedOpen'}"
data = eval(line)
sorted(data.items(), key=lambda pair: line.index("'%s','%s'" % pair)

which gives me: 这给了我:

[('InventoryTake', 'Key'),
('OtherSceneNode', 'Shed'),
('AddOtherScene', 'ShedOpen')]

This should do the trick, and is shorter than most of the other solutions. 这应该可以解决问题,并且比大多数其他解决方案都要短。

from collections import OrderedDict

data = []
for line in eventVar.readline():
    # Remove braces
    line = line.strip()[1:-1]
    results = OrderedDict()
    # Split by comma sign
    for pair in line.split(','):
        # Get key and value by splitting on colon
        key, value = pair.split(':')
        # Use eval to get rid of quotation surrounding the key and value
        results[eval(key)] = eval(value)
        # Add the results from reading this line to a list
        data.append(results)

This got a bit wordy, but it appears to do what you're asking for: 这有点罗嗦,但它似乎做你要求的:

#!/usr/local/cpython-3.3/bin/python

import shlex
import collections

def strip_single_quote(string):
    assert string[0] == "'"
    assert string[-1] == "'"
    return string[1:-1]

def dict_to_tuples(string):
    list_ = list(shlex.shlex(string))
    assert list_[0] == '{'
    assert list_[-1] == '}'
    list_ = list_[1:-1]
    print(list_)
    len_list = len(list_)

    for base_index in range(0, len_list, 4):
        assert list_[base_index + 1] == ':'
        if list_[base_index + 3:]:
            assert list_[base_index + 3] == ','
        key = strip_single_quote(list_[base_index + 0])
        value = strip_single_quote(list_[base_index + 2])
        yield (key, value)

def main():
    string = "{'InventoryTake':'Key','OtherSceneNode':'Shed','AddOtherScene':'ShedOpen'}"
    od = collections.OrderedDict(dict_to_tuples(string))
    print(od)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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