Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

Python: list() as default value for dictionary

I have Python code that looks like:

if key in dict:
  dict[key].append(some_value)
else:
  dict[key] = [some_value]

but I figure there should be some method to get around this 'if' statement. I tried

dict.setdefault(key, [])
dict[key].append(some_value)

and

dict[key] = dict.get(key, []).append(some_value)

but both complain about "TypeError: unhashable type: 'list'". Any recommendations? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best method is to use collections.defaultdict with a list default:

from collections import defaultdict
dct = defaultdict(list)

Then just use:

dct[key].append(some_value)

and the dictionary will create a new list for you if the key is not yet in the mapping. collections.defaultdict is a subclass of dict and otherwise behaves just like a normal dict object.

When using a standard dict, dict.setdefault() correctly sets dct[key] for you to the default, so that version should have worked just fine. You can chain that call with .append():

>>> dct = {}
>>> dct.setdefault('foo', []).append('bar')  # returns None!
>>> dct
{'foo': ['bar']}

However, by using dct[key] = dct.get(...).append() you replace the value for dct[key] with the output of .append(), which is None.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...