欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python學習筆記:字典的使用示例詳解

 更新時間:2014年06月13日 09:56:44   投稿:hebedich  
python字典的使用: python字典有很多好用的地方。字典每個元素都有鍵和值。如同現(xiàn)代漢語字典中的拼音和對應的文字。字典中的鍵是唯一的,而值不一定唯一。你看,和現(xiàn)代漢語字典多么的相似。

經(jīng)典字典使用函數(shù)
dict:通過其他映射(比如其他字典)或者(鍵,值)這樣的序列對建立字典。當然dict成為函數(shù)不是十分確切,它本質(zhì)是一種類型。如同list。

復制代碼 代碼如下:

items=[('name','zhang'),('age',42)]
d=dict(items)
d['name']

len(d):返回項的數(shù)量
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的區(qū)別。

復制代碼 代碼如下:

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:將字典中的鍵以列表的方式返回。(注意區(qū)分和items的區(qū)別)

iterkeys:返回針對鍵的迭代器。

pop:獲得對應給定鍵的值,然后將鍵-值對刪除。

popitem:彈出一個隨機的項,

setdefault:既能獲得與給定鍵相關(guān)的值,又能在字典中不含有該鍵的情況下設定相應的鍵值。

update:用一個字典更新另一個字典。

復制代碼 代碼如下:

d={'1':'d','2':'s','3':'a'}
x={'1','jk'}
d.update(x)

values:以列表的形式返回字典中的值。

itervalues:返回值得迭代器。

相關(guān)文章

最新評論