Python Dictionaries

dict函数

Python Dictionaries_第1张图片
 

基本的字典操作

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])

 运行结果如下所示:
Python Dictionaries_第2张图片
 

字典的格式化字符串
Python Dictionaries_第3张图片
 

字典方法:clear、copy、fromkeys、get

Python Dictionaries_第4张图片
Python Dictionaries_第5张图片
Python Dictionaries_第6张图片

 

接下来改写上面那个代码,使用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)

运行结果如下所示:

Python Dictionaries_第7张图片
 

has_key、items、iteritems、keys、iterkeys、values、itervalues

Python Dictionaries_第8张图片
Python Dictionaries_第9张图片
 

pop、popitem、setdefault、update

Python Dictionaries_第10张图片
Python Dictionaries_第11张图片

Summary


 

你可能感兴趣的:(python)