如何从Python中的文件中读取多个字典? [英] how to read multiple dictionaries from a file in python?

查看:982
本文介绍了如何从Python中的文件中读取多个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相对较新的python。
我正在尝试阅读一个ascii文件,其中有多个字典。该文件具有以下格式。

  {Key1:value1 
key2:value2
...
}
{Key1:value1
key2:value2
...
}
{
...

文件中的每个字典都是一个嵌套字典。
我正在试图把它作为一个字典列表来阅读。有没有简单的方法来做到这一点?
i已经尝试了下面的代码,但它似乎并没有工作

  data = json.load(open('因为你的数据在你的数据库中,所以你可以使用这个数据库中的数据来创建数据库。输入文件并不是真正的JSON或Python对象文字格式,你将需要自己解析它。您没有真正指定字典中允许的键和值,因此以下字段只能是字母数字字符串。因此给定一个名为 doc.txt 的输入文件: 

  {key1:value1 
key2:value2
key3:value3
}
{key4:value4
key5:value5
}

以下读取和转换它转换成由字母数字键和值组成的字典的Python列表:

  from pprint import pprint 
import re

dictpat = r'\ {((?:\ s * \ w + \s *:\ s * \ w + \s *)+)\}'#not non捕获(?:)内部组
itempat = r'(\s *(\w +)\s *:\s *(\w +)\s *)'#在这个表达式

中打开('doc.txt')作为f:
lod = [{group [1]:group [2] for re.findall(itempat, )}
for re.findall(dictpat,f.read())]

pprint(lod)

输出:

  [{'key1':'value1','key2':'value2','key3 ':'value3'},
{'key4':'value4','key5':'value5'}]


I am relatively new to python. I am trying to read an ascii file with multiple dictionaries in it. The file has the following format.

{Key1: value1
 key2: value2
 ...
}
{Key1: value1
 key2: value2
 ...
}
{
...

Every dictionary in the file is a nested dictionary. I am trying to read it as a list of dictionaries. is there any simple way to do this? i have tried the following code but it doesn't seem to work

data = json.load(open('doc.txt'))

解决方案

Since the data in your input file isn't really in JSON or Python object literal format, you're going to need to parse it yourself. You haven't really specified what the allowable keys and values are in the dictionary, so the following only allows them to be alphanumeric character strings.

So given an input file with the following contents nameddoc.txt:

{key1: value1
 key2: value2
 key3: value3
}
{key4: value4
 key5: value5
}

The following reads and transforms it into a Python list of dictionaries composed of alphanumeric keys and values:

from pprint import pprint
import re

dictpat = r'\{((?:\s*\w+\s*:\s*\w+\s*)+)\}' # note non-capturing (?:) inner group
itempat = r'(\s*(\w+)\s*:\s*(\w+)\s*)'      # which is captured in this expr

with open('doc.txt') as f:
    lod = [{group[1]:group[2] for group in re.findall(itempat, items)}
                                for items in re.findall(dictpat, f.read())]

pprint(lod)

Output:

[{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'},
 {'key4': 'value4', 'key5': 'value5'}]

这篇关于如何从Python中的文件中读取多个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆