国产探花免费观看_亚洲丰满少妇自慰呻吟_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'

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 奇台县| 邮箱| 手游| 阿鲁科尔沁旗| 永定县| 厦门市| 咸宁市| 西贡区| 平安县| 和龙市| 赤水市| 南投县| 马尔康县| 积石山| 怀安县| 屏东市| 鲁山县| 新化县| 宁波市| 阿鲁科尔沁旗| 普宁市| 东明县| 德令哈市| 大新县| 仁寿县| 油尖旺区| 汪清县| 松阳县| 郸城县| 平顶山市| 盱眙县| 金寨县| 房产| 弥勒县| 靖宇县| 汉沽区| 临泉县| 丰县| 张家口市| 千阳县| 杂多县|