专栏名称: 志军
分享Python相关技术干货,偶尔扯扯其它的
目录
相关文章推荐
Python开发者  ·  外网热议:为什么 DeepSeek ... ·  13 小时前  
51好读  ›  专栏  ›  志军

Python:关于高效使用字典的清单

志军  · 公众号  · Python  · 2017-08-22 11:43

正文

请到「今天看啥」查看全文


d = {'name': 'python'}
if 'name' in d:
   print(d['hello'])
else:
   print('default')

good

print(d.get("name", "default"))

3、用 setdefault 为字典中不存在的 key 设置缺省值

data = [
       ("animal", "bear"),
       ("animal", "duck"),
       ("plant", "cactus"),
       ("vehicle", "speed boat"),
       ("vehicle", "school bus")
   ]

在做分类统计时,希望把同一类型的数据归到字典中的某种类型中,比如上面代码,把相同类型的事物用列表的形式重新组装,得到新的字典

groups = {}

>>>
{'plant': ['cactus'],
'animal': ['bear', 'duck'],
'vehicle': ['speed boat', 'school bus']}

普通的方式就是先判断 key 是否已经存在,如果不存在则要先用列表对象进行初始化,再执行后续操作。而更好的方式就是使用字典中的 setdefault 方法。







请到「今天看啥」查看全文