国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-23 05:28:54
字體:
來源:轉載
供稿:網友

經典字典使用函數
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'

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 商水县| 乐山市| 浠水县| 衡东县| 浮山县| 永清县| 汉中市| 济宁市| 徐水县| 天峻县| 宾阳县| 开化县| 大田县| 巍山| 莆田市| 灌云县| 汝南县| 彭山县| 玉门市| 吉木萨尔县| 佳木斯市| 衡东县| 温州市| 桐庐县| 吉林省| 鸡东县| 上高县| 科尔| 十堰市| 民丰县| 株洲市| 庄浪县| 锡林郭勒盟| 大渡口区| 郓城县| 景洪市| 甘肃省| 论坛| 电白县| 张家口市| 衡东县|