[英]How to create a dictionary from a dictionary in python?
Date Subject Maths Science English French Spanish German
16:00:00 Uploaded 100 95 65 32 23 45
17:00:00 Unknown 45 53 76 78 54 78
18:00:00 Captured 43 45 56 76 98 34
Date BoardType Maths Science English French Spanish German
16:00:00 CBSE 50 95 65 32 23 45
17:00:00 NTSE 45 53 76 78 54 78
18:00:00 YTTB 100 45 56 76 98 34
我的文本文件dataVal.txt中有这两个表。
我希望输出像:
'Subject':'Uploaded':'16:00:00':'Maths':'100',Science :: 95 ....诸如此类。 基本上,“主题”是第一个表的主键,该表的值为“ Uploaded”,然后“ Uploaded”成为值为“ 16:00:00”的键,然后成为键并具有Maths ,科学,英语等,其进一步的值分别为100、95、65等。
dic = dict()
with open('C:\\Users\\aman.seth\\Documents\\dataVal.txt','r') as fh:
for l in fh.readlines():
try:
lines = l.split('\t')
date, sub, num = lines[0], lines[1], [str(x) for x in lines[2:]]
dic.setdefault(sub, {})
dic[sub][date] = num
except Exception as er:
print er
print dic
到目前为止,这是我所做的,但是我猜这还不够准确。
请尝试此操作,并进行修复:
import re
dic = dict()
with open('txt', 'r') as fh:
memory = None
for line in fh.readlines():
lines = line.rstrip('\n')
if line.split():
try:
match = re.search('(BoardType|Subject)', line)
if match:
memory = match.group(1)
dic.setdefault(memory, {})
header = line.split()
mark_index = header[2:]
else:
mark_dict = dict()
lines = [ x for x in line.split(' ') if x]
date, sub, num = lines[0], lines[1], [str(x) for x in lines[2:]]
dic[memory].setdefault(sub, {})
mark = dict(zip(mark_index, num))
dic[memory][sub][date] = mark
except Exception as error:
print 'Error: ', error
import pprint
pprint.pprint(dic)
输出:
{'BoardType': {'CBSE': {'16:00:00': {'English': '65',
'French': '32',
'German': '45',
'Maths': '50',
'Science': '95',
'Spanish': '23'}},
'NTSE': {'17:00:00': {'English': '76',
'French': '78',
'German': '78',
'Maths': '45',
'Science': '53',
'Spanish': '54'}},
'YTTB': {'18:00:00': {'English': '56',
'French': '76',
'German': '34',
'Maths': '100',
'Science': '45',
'Spanish': '98'}}},
'Subject': {'Captured': {'18:00:00': {'English': '56',
'French': '76',
'German': '34\n',
'Maths': '43',
'Science': '45',
'Spanish': '98'}},
'Unknown': {'17:00:00': {'English': '76',
'French': '78',
'German': '78\n',
'Maths': '45',
'Science': '53',
'Spanish': '54'}},
'Uploaded': {'16:00:00': {'English': '65',
'French': '32',
'German': '45\n',
'Maths': '100',
'Science': '95',
'Spanish': '23'}}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.