dict函数
基本的字典操作
len(d)返回d中项(key-value)的数量
d[k]返回关联到键k上的值
d[k]=v将值v关联到键k上
del d[k]删除键为k的项
k in d检查d中是否有含有键为k的项
来看个简单的例子
databases = { "Oracle" : { "username" : "oracleapp", "password" : "oracleapp123" }, "Db2" : { "username" : "db2app", "password" : "db2app123" }, "MongoDB" : { "username" : "mongodbapp", "password" : "mongodbapp123" } } labels = { "username" : "DB Username", "password" : "DB Password" } name = raw_input("DB Name : ") request = raw_input("DB Username(u) or DB Password(p)? ") if request == "u" : key = "username" if request == "p" : key = "password" if name in databases : print "%s database's %s is %s." % (name, labels[key], databases[name][key])
字典方法:clear、copy、fromkeys、get
接下来改写上面那个代码,使用get方法来访问实体
databases = { "Oracle" : { "username" : "oracleapp", "password" : "oracleapp123" }, "DB2" : { "username" : "db2app", "password" : "db2app123" }, "MongoDB" : { "username" : "mongodbapp", "password" : "mongodbapp123" } } labels = { "username" : "DB Username", "password" : "DB Password" } name = raw_input("DB Name : ") request = raw_input("DB Username(u) or DB Password(p)? ") if request == "u" : key = "username" elif request == "p" : key = "password" else : key = request db = databases.get(name, {}) label = labels.get(key, key) result = db.get(key, "not available") print "%s database's %s is %s." % (name, label, result)
运行结果如下所示:
has_key、items、iteritems、keys、iterkeys、values、itervalues
pop、popitem、setdefault、update