追加到Python字典列表 [英] Appending to list in Python dictionary

查看:155
本文介绍了追加到Python字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更优雅的方式来编写这段代码?



我在做什么:我有钥匙和日期。可以有一些日期分配给一个键,所以我正在创建一个日期列表的字典来代表这个。以下代码工作正常,但我希望能够使用更优雅的Pythonic方法。

  dates_dict = dict()
为键,日期为cur:
如果键在dates_dict:
dates_dict [key] .append(date)
else:
dates_dict [key] = [date]

我期待下面的工作,但我不断得到一个NoneType没有属性附加错误。

  dates_dict = dict()
为键,日期为cur:
dates_dict [key] = dates_dict .get(key,[])。append(date)

这可能与事实上,

  print([]。append(1))

但为什么?

解决方案

list.append 返回,因为它是一个就地操作,你将它分配回 dates_dict [键] 。所以,下一次当你执行 dates_dict.get(key,[])。append 你实际上在做 None.append 。这就是为什么它是失败的。相反,您可以简单地执行

  dates_dict.setdefault(key,[])。append(date)

但是,我们有 collections.defaultdict 仅供参考。你可以这样做

 从集合import defaultdict 
dates_dict = defaultdict(list)
为键,日期在cur:
dates_dict [key] .append(date)

这将创建如果在字典中找不到,则新的列表对象。



注意: strong>由于 defaultdict 将创建一个新列表,如果该字典中没有找到该键,这将产生无意的副作用。例如,如果您只想要检索一个不存在的密钥的值,那么它将创建一个新的列表并返回。


Is there a more elegant way to write this code?

What I am doing: I have keys and dates. There can be a number of dates assigned to a key and so I am creating a dictionary of lists of dates to represent this. The following code works fine, but I was hoping for a more elegant and Pythonic method.

dates_dict = dict() 
for key,  date in cur:
    if key in dates_dict:
        dates_dict[key].append(date)
    else:
        dates_dict[key] = [date] 

I was expecting the below to work, but I keep getting a NoneType has no attribute append error.

dates_dict = dict() 
for key,  date in cur:
    dates_dict[key] = dates_dict.get(key, []).append(date) 

This probably has something to do with the fact that

print([].append(1)) 
None 

but why?

解决方案

list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date)

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

This will create a new list object, if the key is not found in the dictionary.

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

这篇关于追加到Python字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆