我有一个文本文件,其结构数据如下所示:
from application import app, db
from twisted.internet import defer
from bson.json_util import dumps
@app.route('/')
def home(request):
return 'Hello, world!'
@app.route('/teste', methods=['POST', 'GET', 'DELETE'])
@defer.inlineCallbacks
def teste(request):
if request.method == 'POST':
body = json.loads(request.content.read())
yield db.insert('teste', body)
defer.returnValue(return_json(request, {'success': True}))
elif request.method == 'GET':
body = yield db.find_one('teste', {})
defer.returnValue(return_json(request, body))
elif request.method == 'DELETE':
yield db.drop('teste')
defer.returnValue(return_json(request, {'success': True}))
def return_json(request, result):
request.setHeader('Content-Type', 'application/json')
return dumps(result)
在具有以下结构的python字典中转换它的最佳方法是什么?
item {
id: 1
name: 'abc'
}
item {
id: 2
name: 'def'
}
编辑:很抱歉没有立即发布我的尝试:
{'abc': 1, 'def', 2}
答案 0 :(得分:0)
您可以遍历文件并找到id, name
对:
import re
file_data = [i.strip('\n').lstrip() for i in open('filename.txt')]
line_data = [[int(b) if b.isdigit() else b[1:-1] if b.startswith("'") else b for b in re.split(':\s*', i)] for i in file_data if re.findall('[a-zA-Z]+:\s', i)]
grouped_data = [line_data[i:i+2] for i in range(0, len(line_data), 2)]
last_data = dict([[b[-1] for b in i][::-1] for i in grouped_data])
输出:
{'abc': 1, 'def': 2}
答案 1 :(得分:0)
我在编辑器中一起攻击的超级最小解决方案(没有涉及正则表达式)
with open('test.txt', 'r') as f:
res: dict = {}
lst_file = list(f)
for i in range(0, len(lst_file), 4):
key = lst_file[i+2].strip().replace('name: ', '').strip('\'')
value = int(lst_file[i+1].strip().replace('id: ', ''))
res[key] = value # update your dictionary
print(res)
你也可以像dict一样理解
with open('test.txt', 'r') as f:
lst_file = list(f)
res = {lst_file[i+2].strip().replace('name: ', '').strip('\''): int(lst_file[i+1].strip().replace('id: ', '')) for i in range(0, len(lst_file), 4)}
print(res)
虽然,我不得不承认,对于所有后续的字符串操作它并不那么美丽......但是,鉴于稀疏的解释,这应该可以胜任!
鉴于您的尝试到目前为止,您还可以混合我们的解决方案,产生以下结果:
with open('test.txt', 'r') as f:
res: dict = {}
lst_file = list(f)
for i in range(0, len(lst_file), 4):
key = lst_file[i+2].split('\'')[1]
value = int(lst_file[i+1].split(':')[1])
res[key] = value # update your dictionary
print(res)
您可以自己完成对此解决方案的理解。希望它有所帮助。