欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python学习笔记:字典的使用示例详解

程序员文章站 2023-11-26 12:01:16
经典字典使用函数dict:通过其他映射(比如其他字典)或者(键,值)这样的序列对建立字典。当然dict成为函数不是十分确切,它本质是一种类型。如同list。 复制代码 代...

经典字典使用函数
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'
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:将字典中的键以列表的方式返回。(注意区分和items的区别)

iterkeys:返回针对键的迭代器。

pop:获得对应给定键的值,然后将键-值对删除。

popitem:弹出一个随机的项,

setdefault:既能获得与给定键相关的值,又能在字典中不含有该键的情况下设定相应的键值。

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

复制代码 代码如下:

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

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

itervalues:返回值得迭代器。