字典用法补充

之前基础篇博客中只是总结了一下字典的基本用法,这里对字典功能进行一些补充,毕竟作为使用频率较高的数据类型,还是要重点掌握的。废话不多说,上重点:

1、字典是python中唯一内建的映射类型。(通过名字引用值的数据结构称为映射)

2、字典中的键是唯一的

3、dict()内建函数,参数可以是键与值的序列,可以是关键字参数,也可以是其他的映射。如果不给dict提供参数,则会返回一个空字典(a=dict()-->a={})。

#通过向dict函数传递参数来创建字典

tina=dict(height=165,weight=44,hair='black')
print(tina,tina['hair'])
#{'weight': 44, 'hair': 'black', 'height': 165} black

小练习:

#电话簿的案例:
people={
    'tina':{
        'phone':123,
        'address':'beijing'
    },
    'fei':{
        'phone':34444,
        'address':'tianjin'
    }
}
#方法一:
name = input('input your name:')
for i in people:
    if name==i:
        print('%s %s is %d;%s %s is %s'
              %(name,'phone',people[name]['phone'],name,'address',people[name]['address']))

#方法二:
lables={
    'phone':'phone number is',
    'address':'address is'
}
name=input('input your name:')
key=input('Phone number(p) or address(a):')
if key=='p':key='phone'
if key=='a':key='address'
if name in people:
    print('%s %s is %s'%(name,lables[key],people[name][key]))
else:quit

字典格式化字符串的用法:

table = {'Alice':457819,'Bill':929181,'Candy':826213}
print('Bill`s phone number is %(Bill)d'%table)#Bill`s phone number is 929181

 清空字典:

table = {'Alice':457819,'Bill':929181,'Candy':826213}
table.clear()
print(table)#{}

根据键创建新的字典:

x={}.fromkeys(['name','age'])
print(x,x.fromkeys(['age']))
执行结果:
{'name': None, 'age': None} {'age': None}

用可迭代对象为参数,且每一个迭代对象为(k,v)对

l1=[1,2,3]
l2=['tina','tom','fei']
d=dict(zip(l1,l2))
print(d)#{1: 'tina', 2: 'tom', 3: 'fei'}

 字典推导式:

d={c:ord(c) for c in 'abc'}
print(d)#{'b': 98, 'c': 99, 'a': 97}

 

小练习:(字符统计,返回字典)

d={}
s='hello haha'
for c in s:
    if c in d:
        d[c]+=1
    else:
        d[c]=1
print(d)

结果:
{'a': 2, ' ': 1, 'h': 3, 'l': 2, 'o': 1, 'e': 1}
#方法二:
d={}
s='hello haha'
for c in s:
    d[c]=d.setdefault(c,0)+1#dict自带的setdefault方法,会在key存在时返回value,若不存在,则设为指定值并返回这个值。
    print(d)

 

 

posted @ 2016-06-13 13:54  tina.py  阅读(520)  评论(0编辑  收藏  举报