經典字典使用函數
dict:通過其他映射(比如其他字典)或者(鍵,值)這樣的序列對建立字典。當然dict成為函數不是十分確切,它本質是一種類型。如同list。
items=[('name','zhang'),('age',42)]
d=dict(items)
d['name']
len(d):返回項的數量
d[k]:返回鍵k上面的值。
d[k]=v:將k對應的值設置為k。
del d[k]:刪除字典中的這一項。
k in d:檢查d中是否含有鍵為k的項。注:只能查找鍵,不能查找值。
簡單的電話本示例:
# A simple database
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
people = {
??? 'Alice': {
??????? 'phone': '2341',
??????? 'addr': 'Foo drive 23'
??? },
??? 'Beth': {
??????? 'phone': '9102',
??????? 'addr': 'Bar street 42'
??? },
??? 'Cecil': {
??????? 'phone': '3158',
??????? 'addr': 'Baz avenue 90'
??? }
}
# Descriptive labels for the phone number and address. These will be used
# when printing the output.
labels = {
??? 'phone': 'phone number',
??? 'addr': 'address'
}
name = raw_input('Name: ')
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in
# our dictionary:
if name in people: print "%s's %s is %s." % \
??? (name, labels[key], people[name][key])
字典方法
clear:清除字典中的所有項。
x.clear()
copy:淺復制字典。
y=x.copy()
deepcopy:同樣是復制,來看看和copy的區別。
from copy import deepcopy
d={}
d['names']=['as','sa']
c=d.copy()
dc=deepcopy(d)
d['names'].append('ad')
fromkeys:給指定的鍵建立新的字典,每個鍵默認對應的值為none.
{}.fromkeys(['name','age'])
get:更為寬松的訪問字典項的方法。
d.get('name')
# A simple database using get()
# Insert database (people) from Listing 4-1 here.
labels = {
??? 'phone': 'phone number',
??? 'addr': 'address'
}
name = raw_input('Name: ')
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
# Use the correct key:
key = request # In case the request is neither 'p' nor 'a'
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Use get to provide default values:
person = people.get(name, {})
label = labels.get(key, key)
result = person.get(key, 'not available')
print "%s's %s is %s." % (name, label, result)
has_key:檢查字典中是否含有給定的鍵。d.haos_key()。值返回True ,False。
items:將所有字典項目一列表方式返回。
iteritems:方法大致相同,但是會返回一個迭代器而不是列表。
keys:將字典中的鍵以列表的方式返回。(注意區分和items的區別)
iterkeys:返回針對鍵的迭代器。
pop:獲得對應給定鍵的值,然后將鍵-值對刪除。
popitem:彈出一個隨機的項,
setdefault:既能獲得與給定鍵相關的值,又能在字典中不含有該鍵的情況下設定相應的鍵值。
update:用一個字典更新另一個字典。
d={'1':'d','2':'s','3':'a'}
x={'1','jk'}
d.update(x)
values:以列表的形式返回字典中的值。
itervalues:返回值得迭代器。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
