返回顶部

收藏

Dictionary setdefault

更多
#The setdefault method is somewhat similar to get, except that in addition to the get 
#functionality, setdefault sets the value corresponding to the given key if it is not 
#already in the dictionary:

d = {}
print d.setdefault('name', 'N/A')
print  d

d['name'] = 'Gumby'
d.setdefault('name', 'N/A')

print d

#As you can see, when the key is missing, setdefault returns the default and updates 
#the dictionary accordingly. If the key is present, its value is returned and the 
#dictionary is left unchanged. The default is optional, as with get; if it is left 
#out, None is used:

d = {}
print d.setdefault('name')

print d

标签:Python,Dictionary

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. Tamim Shahriar (nore 发表 2012-12-10 17:28:37 Concatenate Two Dictionaries | Python How To?
  2. Tamim Shahriar (nore 发表 2011-10-29 03:28:10 Pythonic way to convert a list into dictionary
  3. 博主 发表 2012-08-24 04:19:00 R中媲美Python Dictionary的神器-hash
  4. 祥子 发表 2014-02-21 07:44:22 Python中的字典
  5. Tamim Shahriar (nore 发表 2012-10-21 01:50:51 MySQLdb Warning: Field x doesn't have a default va
  6. liuzhantao 发表 2016-07-10 07:04:46 Python必知模块库
  7. noreply@blogger.com 发表 2009-11-05 18:12:00 Python in the Scientific World
  8. Timothy Qiu 发表 2016-07-14 13:06:00 Python 3 的 surrogateescape
  9. Brett Cannon (norepl 发表 2011-03-20 17:56:54 PyCon 2011 wrap-up
  10. zrong 发表 2016-07-23 09:15:37 部署Flask + uWSGI + Nginx
  11. 博主 发表 2005-11-06 08:00:00 Python Editor/IDE
  12. robin 发表 2016-07-26 23:27:06 Python网络爬虫1 – 简单的Http请求

发表评论