简体   繁体   中英

How to append a value on the same key in dictionary of python?

I am trying to append a value to the same key in a dictionary. (Finally, What I want to make is a dictionary with one key and two values)

keys = list(dictionary.keys())
for k in keys:
    dictionary.setdefault(k, []).append(0)

But it returns error:

AttributeError: 'int' object has no attribute 'append'

How can I resolve this error?

The dictionary already has values of int types; dictionary.setdefault(k, []) will returns the int object which does not have append method.

You need to convert int object to list .

  • One way: use list of ints from the beginning instead int. ( [0] instead of 0 )
  • Other way: convert int to list before appending.

I recommend the first way for consistency.

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