简体   繁体   中英

How to add multiple values to dictionary keys in Python

I am trying to add a value (string) to the dictionary I already have in this form:

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']}

Already tried the How to add multiple values in dictionary having specific key solution as myDictionary[key].append(value) would yell a AttributeError: *str* object has no attribute *append* Error so using [myDictionary['key'], item3] was the way to add the second but not the third value for the key, key.

As requested, this is the actual code that I am trying to run:

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

And this one issues a AttributeError: 'str' object has no attribute 'extend'error

I can also confirm that running this simplified code:

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

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

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

print(currHostDict)

outputs the expected {'en0': ['item1', 'item2', 'item3']} .

However, this assumes the dictionary already has at least one key and at least one value for that key as I am creating in the original code through currHostDict[adapter] = macIp

Please also note that the else statement will always run first so the dictionary is always filled out with at least one key and its value.

In your code, the problem comes from the line:

            currHostDict[adapter] = macIp

Because macIp is a str and not a list of str . The obvious fix is the following:

            currHostDict[adapter] = [macIp]

Moreover, I advise you to check the defaultdict structure. If you request a non-existent key in a defaultdict, it will initialize it with the given default value.

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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM