[英]Create Dictionary of Dictionary at Run time in python from a data from a file
我们如何在运行时使用python创建字典的下方字典。
当将数据手动存储在字典中时,具有所需输出的附加代码段。
何时从InputFile中获取输入???
输入文件
00
称为999000
VLR 365444564544
致电2756565
16
原因码12
4级
严重程度轻微
剧本:
Operation = {'00': {'Called': '999000', 'calling': '2756565', 'vlr': '365444564544'},
'16': {'reason_code': '12'}
}
for op_id, op_info in Operation.items():
print("\n Operation ID:", op_id)
for key in op_info:
print(key + ':', op_info[key])
OUTPUT
Operation ID: 00
Called: 999000
vlr: 365444564544
calling: 2756565
Operation ID: 16
reason_code: 12
level :4
severity :minor
当从InputFile提取Input时,如何在python中创建上述字典的字典?
看起来只有键的行可以通过对其中的单词进行计数来检测,然后可以使用该键直到有新的键为止。 这是一个示例实现:
def file2dict(file_name):
with open(file_name) as f:
res = dict() # result
key = "" # we keep the key until there is a new one
for line in f.readlines():
words = line.split() # get words in lines
if (words): # check if the line was not empty
if (len(words) == 1): # if the length is one, we know this is a new key
key = words[0] # and we change the key in use
res[key] = dict() # and create a dict element
else:
res[key][words[0]] = words[1] # and add key-value pairs in each line
return res
测试一下:
print(file2dict("in.txt")) # your example file
输出:
{'00': {'Called': '999000', 'VLR': '365444564544', 'Calling': '2756565'}, '16': {'reason_code': '12', 'level': '4', 'severity': 'minor'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.