python defaultdict(list),Python:list()作为字典的默认值

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!

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值