gpt4 book ai didi

python - 如何在Python中向字典键添加多个值

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

我正在尝试将一个值(字符串)添加到我已经采用这种形式的字典中:

item1
item2
item3
    myDictionary = {'key':[item1, item2]}

###Adding the third value (item3) to the already {'key': ['item1', 'item2']} dictionary.

myDictionary['key'] = [myDictionary['key'], item3]

###Ending with 3rd item being placed as a separate list of values:
#{'key': [['item1', 'item2'], item3]}
#instead of getting the expected and desirable:

{'key': ['item1', 'item2', 'item3']}

已经尝试过 How to add multiple values in dictionary having specific key解决方案为 myDictionary[key].append(value) 会大喊 AttributeError: *str* object has no attribute *append* Error 因此使用 [myDictionary[' key'], item3] 是为键 key 添加第二个但不是第三个值的方法。

根据要求,这是我尝试运行的实际代码:

currHostDict = {}
for x in netstatinfo:
result = open("result.txt", "a+")
z = re.match("^en", x)
if z:
adapter = re.split(" +", x)[0]
macIp = re.split(" +", x)[3]
if adapter in currHostDict:
#currHostDict[adapter] = [currHostDict[adapter], macIp]
print(type(currHostDict))
currHostDict[adapter].extend([macIp])
#currHostDict[adapter] = [currHostDict[adapter].extend(macIp)]
#currHostDict[adapter] = [currHostDict[adapter].append(macIp)]
#currHostDict[adapter] = "test"
else:
currHostDict[adapter] = macIp

这会发出 AttributeError: 'str' object has no attribute 'extend' 错误

我还可以确认运行这个简化的代码:

item1 = "item1"
item2 = "item2"
item3 = "item3"

currHostDict = {'en0':[item1,item2]}

currHostDict['en0'].extend([item3])

print(currHostDict)

输出预期的{'en0': ['item1', 'item2', 'item3']}

但是,这假设字典已经具有至少一个键和该键的至少一个值,正如我通过 currHostDict[adapter] = macIp

在原始代码中创建的那样

另请注意,else 语句将始终首先运行,因此字典始终至少填充一个键及其值。

最佳答案

在您的代码中,问题来自以下行:

            currHostDict[adapter] = macIp

因为macIp是一个str,而不是str的列表。明显的修复如下:

            currHostDict[adapter] = [macIp]

此外,我建议您检查 defaultdict 结构。如果您请求 defaultdict 中不存在的键,它将使用给定的默认值对其进行初始化。

from collections import defaultdict

netstatinfo = ["A - - item1", "B - - item4", "A - - item2", "A - - item3"]

currHostDict = defaultdict(lambda: [])
for x in netstatinfo:
adapter = re.split(" +", x)[0]
macIp = re.split(" +", x)[3]
currHostDict[adapter].append(macIp)

print(dict(currHostDict))
# {'A': ['item1', 'item2', 'item3'], 'B': ['item4']}

关于python - 如何在Python中向字典键添加多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59274903/

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