經典字典使用函數
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'
新聞熱點
疑難解答