首页 > 编程 > 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'

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表