首页 > 代码库 > 文件内容转换多层字典(适合新手理解)
文件内容转换多层字典(适合新手理解)
#!/usr/bin/env python
#-*- coding:UTF-8 -*-
flag = 0
return_flag = 0
f = open("file3.txt","r",encoding = "utf-8")
dict1 = {}
dict2 = {}
dict3 = {}
dict4 = {}
dict5 = {}
dict6 = {}
ZN = {}
MSK = {}
US = {}
info1 = {}
for i in f:
if "中国" in i:
list1 = i.strip().split(":")
list1[2] = list1[2].strip().split(",")
list1[4] = list1[4].strip().split(",")
list1[6] = list1[6].strip().split(",")
list1[8] = list1[8].strip().split(",")
dict1[list1[1]] = list1[2]
dict2[list1[3]] = list1[4]
dict3[list1[5]] = list1[6]
dict4[list1[7]] = list1[8]
ZN.update(dict2)
ZN.update(dict1)
ZN.update(dict3)
ZN.update(dict4)
if "美国" in i:
list2 = i.strip().split(":")
list2[2] = list2[2].strip().split(",")
dict5[list2[1]] = list2[2]
US.update(dict5)
if "俄罗斯" in i:
list3 = i.strip().split(":")
list3[2] = list3[2].strip().split(",")
dict6[list3[1]] = list3[2]
MSK.update(dict6)
else:
pass
f.close()
info1["中国"] = ZN
info1["美国"] = US
info1["俄罗斯"] = MSK
while flag == 0:
while return_flag == 0 and flag ==0:
for i in info1:
print(i)
choice1 = input("请选择:")
return_flag = 1
break
while return_flag == 1 and flag == 0:
for i in info1[choice1]:
print(i)
choice2 = input("请输入地名或按键选择(r:返回上一级,q:退出)")
if choice2 == "q":
flag = 1
break
if choice2 == "r":
return_flag = 0
break
return_flag = 2
break
while return_flag == 2 and choice2 in info1[choice1] and flag ==0:
for a in info1[choice1][choice2]:
print(a)
choice3 = input("请输入地名或按键选择(r:返回上一级,q:退出)")
if choice3 == "q":
flag = 1
break
if choice3 == "r":
return_flag = 1
break
else:
print("欢迎来到%s!" % choice3)
flag = 1
break
文件存储内容为:
‘‘‘
中国:北京:东城,西城,大兴,房山:上海:静安,普陀,浦东,金山:广州:天河,越秀,海珠,白云:香港:九龙,北区,大浦,沙田
美国:华盛顿:白宫
俄罗斯:莫斯科:沙皇
‘‘‘
文件内容转换多层字典(适合新手理解)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。