我想基于文本文件构建嵌套字典。例如。 (的text.txt)
...
hostA hostA.testing.com 192.168.1.101
hostB hostB.testing.com 192.168.1.102
...
理想情况下,我想获得以下嵌套字典
...
{'hostA': {'FQHN': 'hostA.testing.com', 'IP': '192.168.1.101'}, 'hostB': {'FQHN': 'hostB.testing.com', 'IP': '192.168.1.102'}}
...
所以我制作了以下Python代码:
myinnerdict={}
myouterdict={}
def main():
my_fh = open('text.txt', 'r')
for line in my_fh:
newline = line.strip().split() # get ride of the '\n' and make it a inner list .
#print(newline)
myinnerdict['FQHN']=newline[1]
myinnerdict['IP']=newline[2]
#print(myinnerdict)
#print(newline[0])
myouterdict[newline[0]]=myinnerdict
print(myouterdict)
if __name__ == "__main__":
main()
...
然而,除了我的理解,当我运行它时我得到了这个结果:
...
{'hostA': {'FQHN': 'hostB.testing.com', 'IP': '192.168.1.102'}, 'hostB': {'FQHN': 'hostB.testing.com', 'IP': '192.168.1.102'}}
...
这不是我想要的,我不知道我错过了什么,请帮助。
答案 0 :(得分:1)
这种情况正在发生,因为您正在为innerdict
重复使用相同的dict对象。您需要在循环中创建一个新的dict对象:
myouterdict={}
def main():
my_fh = open('text.txt', 'r')
for line in my_fh:
myinnerdict={}
newline = line.strip().split() # get ride of the '\n' and make it a inner list .
#print(newline)
myinnerdict['FQHN']=newline[1]
myinnerdict['IP']=newline[2]
#print(myinnerdict)
#print(newline[0])
myouterdict[newline[0]]=myinnerdict
print(myouterdict)
if __name__ == "__main__":
main()
答案 1 :(得分:0)
问题是您正在为字典重用相同的变量。由于myouterdict
存储对变量myinnerdict
的引用而不是实际数据,因此它们都是相同的。例如,试试这个:
>>> a = {}
>>> b = {"my a variable": a}
>>> b
{'my a variable': {}}
>>> a["asdf"] = 3
>>> b
{'my a variable': {'asdf': 3}}
如您所见,b
正在存储a
的引用,而不是a
的空dict数据。您需要做的是.copy()
它(注意.copy()
不会复制dict的内容,但会使新的引用更多地阅读here):
myinnerdict = {}
myouterdict = {}
def main():
my_fh = open('text.txt', 'r')
for line in my_fh:
newline = line.strip().split()
myinnerdict['FQHN'] = newline[1]
myinnerdict['IP'] = newline[2]
# Note this copy here
myouterdict[newline[0]] = myinnerdict.copy()
print(myouterdict)
# Remember to close the file!
my_fh.close()
if __name__ == "__main__":
main()
无论如何,您也可以立即分配新创建的dict对象,而不是使用变量:
mydict = {}
def main():
my_fh = open('test.txt', 'r')
for line in my_fh:
newline = line.strip().split()
mydict[newline[0]] = {"FQHN": newline[1], "IP": newline[2]}
print(mydict)
my_fh.close()
if __name__ == "__main__":
main()