gpt4 book ai didi

python - 在不覆盖现有键值对的情况下更新字典?

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:00 24 4
gpt4 key购买 nike

我有一个如下的输入文件,我可以从中构建我的字典

一般格式

<IP_1>
KEY_1=VALUE_1
KEY_2=VALUE_2

<IP_2>
KEY_1=VALUE_1
KEY_2=VALUE_2

例子

192.168.1.1
USER_NAME=admin
PASSWORD=admin123

192.168.1.2
USER_NAME=user
PASSWORD=user123

预期的字典应该是这样的:

>>print dictionary_of_ip
{'192.168.1.1':{'USER_NAME'='admin','PASSWORD'='admin123'},
'192.168.1.2':{'USER_NAME'='user','PASSWORD'='user123'}}

本质上是字典中的字典

下面是我的代码:

def generate_key_value_pair(filePath, sep='='):
dict_of_ip = {}
slave_properties = {}
with open(filePath, "rt") as f:
for line in f:
stripped_line = line.strip()
if stripped_line and stripped_line[0].isdigit():
#print 'Found Ip'
ip = stripped_line
dict_of_ip[ip] = ''
elif stripped_line and stripped_line[0].isupper():
#print "Found attributes")
key_value = stripped_line.split(sep)
key = key_value[0].strip()
value = key_value[1].strip()
slave_properties[key] = value
dict_of_ip[ip] = slave_properties

return dict_of_ip

我能够按预期获得第一个 IP 及其属性,但第二个 IP 的第二组值覆盖了第一组。

>>print dict_of_ip
{'192.168.1.1': {'USER_NAME': 'user', 'PASSWORD': 'user123'},
'192.168.1.2': {'USER_NAME': 'user', 'PASSWORD': 'user123'}}

dict_of_ip[ip] = slave_properties 导致覆盖。如何防止 '192.168.1.2' 键的值覆盖第一个值?

最佳答案

试试这个:

def generate_key_value_pair(filePath, sep='='):
dict_of_ip = {}
with open(filePath, "rt") as f:
for line in f:
stripped_line = line.strip()
if stripped_line and stripped_line[0].isdigit():
#print 'Found Ip'
slave_properties = {}
ip = stripped_line
dict_of_ip[ip] = ''
elif stripped_line and stripped_line[0].isupper():
#print "Found attributes")
key_value = stripped_line.split(sep)
key = key_value[0].strip()
value = key_value[1].strip()
slave_properties[key] = value
dict_of_ip[ip] = slave_properties

return dict_of_ip

你在哪里使用相同的(修改过的)dict。我没有故意改变你的代码逻辑,只是将 slave_properties = {} 改成了它应该在的地方

您甚至可以删除您的slave_properties 并单独使用dict

def generate_key_value_pair(filePath, sep='='):
dict_of_ip = {}
with open(filePath, "rt") as f:
for line in f:
stripped_line = line.strip()
if stripped_line and stripped_line[0].isdigit():
#print 'Found Ip'
ip = stripped_line
dict_of_ip[ip] = {}
elif stripped_line and stripped_line[0].isupper():
#print "Found attributes")
key_value = stripped_line.split(sep)
key = key_value[0].strip()
value = key_value[1].strip()
dict_of_ip[ip][key] = value

return dict_of_ip

关于python - 在不覆盖现有键值对的情况下更新字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42563750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com