简体   繁体   中英

How to add mutiple values to a key in a dictionary in python?

M = int(input())
mydict = {}
for i in range (M):
    j,k = map(int, input().split())
    try:
        mydict[j].append(k)
    except KeyError :
        mydict[j] = k
print(mydict)

When I run the code:

Traceback (most recent call last):
  File "source_file.py", line 7, in <module>
    mydict[j].append(k)
AttributeError: 'int' object has no attribute 'append'

The problem you are encountering is that the value of the key is initialised as an int (k) instead of a list ([k]) . When you try to call .append on an int you get an AttributeError .

The pythonic way to initialise a key with a default value is to use either dict.setdefault or use a defaultdict so that your value type is initialised as a list when a new key is added.

Using a defaultdict with default_factory=list auto-creates a new list each time a key is added to the dict :

from collections import defaultdict

M = int(input())
mydict = defaultdict(list)    # passing list as the default type

for i in range (M):
    j,k = map(int, input().split())
    mydict[j].append(k)
print(mydict)

Alternatively, you can use dict.setdefault :

M = int(input())
mydict = {}

for i in range (M):
    j,k = map(int, input().split())
    mydict.setdefault(j, []).append(k)   # using setdefault to initialise as a list
print(mydict)

Finally, if you still prefer the use of the except block, change line 8 in the original to mydict[j] = [k]

edit: typo

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