如何提取字符串格式的字典作为有序字典?

2024-06-16 09:56:15 发布

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

我有一个包含python字典的文本文件。{I>当使用这些无序的字典来提取这些无序的结构时。在

>>> import ast
>>> fp = open('file','r')
>>> dic = fp.readline()
>>> dic
"{'7': {'16': 'a', '15': {'10': {'9': {'8': 'a'}}, '12': {'11': 'a'}, '14': {'13': 'a'}}, '6': {'3': {'1': 'a', '2': 'a'}, '5': 'a', '4': 'a'}}}\n"
>>> dic1 = ast.literal_eval(dic.strip())
>>> dic1
{'7': {'6': {'3': {'1': 'a', '2': 'a'}, '5': 'a', '4': 'a'}, '15': {'10': {'9': {'8': 'a'}}, '12': {'11': 'a'}, '14': {'13': 'a'}}, '16': 'a'}}

我需要将这些字典作为有序字典提取为:

^{pr2}$

我试过了,但没用。在

>>> from collections import OrderedDict as od
>>> od(dic.strip())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/collections.py", line 52, in __init__
    self.__update(*args, **kwds)
  File "/usr/lib/python2.7/_abcoll.py", line 547, in update
    for key, value in other:
ValueError: need more than 1 value to unpack

有没有办法把这些词典提取成有序词典。任何帮助都将不胜感激。在


Tags: inimport字典usrlineastcollectionsfile
1条回答
网友
1楼 · 发布于 2024-06-16 09:56:15

这里我建议的是一种方法,而不是完整的解决方案,因为我没有时间详细阐述一些充分工作和优化的代码。。。在

import collections

dict_names_list = []
dict_list = []
with open('file.txt','r') as txt:
    with open("dicts.py", "wt") as py:
        d = 1
        for line in txt:
            d_name = 'd'+str(d)
            dict_names_list.append(d_name)
            py.write(d_name + ' = ' + line)
            d += 1

dicts = __import__('dicts')

for d in dict_names_list:
    dict_x = collections.OrderedDict()
    dict_x = getattr(dicts, d)
    dict_list.append(dict_x)

这里的策略是将txt文件复制到一个.py文件中,在这些dict中添加变量名(d1,d2,ecc..) 这样你就可以直接导入它们了。在

我写的代码将dicts加载为有序dicts,但顺序仅限于第一个lever ok键,内部dict是无序加载的。。在

我猜你可以试着优化这个“直到一个有序的dicts的有序dicts…”。。在

编辑:您还必须删除“字典.py“导入结束时的文件。。在

相关问题 更多 >