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

2024-06-16 11:09:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下内容的文本文件:

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

以及从文本文件中检索数据的代码:

^{pr2}$

我遇到的问题是,由于字典运行的代码的性质,我需要把它整理好。但是python以随机顺序存储字典键。在

我试过用有序字典来保持顺序,但这没什么区别。我认为这是因为当有序字典获得信息时,它已经按照从文件中读入的内容进行了排序。在

我尝试过eval、literal_eval和json解析器来正确读取数据,但是在运行程序时,字典总是以错误的顺序出现。在

程序这一部分的目的是允许文本文件字典存储尽可能多的这些对(OtherSceneNode和AddOtherScene/taketherscene)。所以我不能假设只有一组键值对。在

我使用的是python 2.7.5,如果它有助于排序,那么它的输出顺序是:

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

我可以重做文本文件以获得特定的行,但这将使我的文本文件更加复杂,我觉得这只是为了避免问题而不是解决问题。在


Tags: 数据key代码程序字典排序顺序eval
3条回答

这有点罗嗦,但似乎符合您的要求:

#!/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)

一种方法是在字符串中查找已解析的数据对,以找到它们的原始相对顺序:

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

这给了我:

^{pr2}$

这应该能做到这一点,而且比其他大多数解决方案都要短。在

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)

相关问题 更多 >