python学习笔记——当索引行不通时

字典(dict)
phonebook={'cc':'12334','dd':'123443'}

phonebook('cc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
phonebook(cc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cc' is not defined
s=dict(phonebook)
s
{'cc': '12334', 'dd': '123443'}
s(cc)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'cc' is not defined
s('cc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable
phonebook
{'cc': '12334', 'dd': '123443'}
phonebook('cc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not callable

phonebook['cc']
'12334'
dict函数:从其它映射或键——值对序列创建字典
items=[('name',lx),('age',26)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'lx' is not defined

items=[('name','lx'),('age',26)]
c=dict(items)
c
{'name': 'lx', 'age': 26}

d=dict()

d
{}
如果未定义字典将返回空字典

dict基本操作
len(d):返回d包含的项数
d[k]:返回d中第k项值
d[k]=v:给d中第K项赋值
del d[k]:删除
k in d:查询在d中是否有k键
dict中没有的元素也可以通过外部直接赋值添加,不像list需要append

d[10]='kk'
d
{10: 'kk'}

x=[]
x[30]='kk'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
x={}
x[30]='kk'
x
{30: 'kk'}
书上练习的一小段
people={
'lx':{
'phone':'123',
'addr':'fdfsf'
},
'sdy':{
'phone':'456',
'addr':'test'
},
'sb':{
'phone':'789',
'addr':'test1'
}

}
labels={'phone':'phonenumber',
'addr':'address'
}
name=input('Name:')
r=input('Please input number(p) or address(a)')
if r=='p':key='phone'
if r=='a':key='addr'
if name in people:print("{}'s {} is {}".format(name,labels[key],people[name][key]))
字符串格式功能用于dict:format_map()
查询关键字对应替换

字典方法:
clear:清除dict内所有项

d={}
d
{}
d{'name'}='lx'
File "<stdin>", line 1
d{'name'}='lx'
^
SyntaxError: invalid syntax
d['name']='lx'
d
{'name': 'lx'}
c{}=d.clear()
File "<stdin>", line 1
c{}=d.clear()
^
SyntaxError: invalid syntax
c{}.clear()
File "<stdin>", line 1
c{}.clear()
^
SyntaxError: invalid syntax
c=d.clear()
c
d
{}
copy:从A dict复制到B dict
x={'name':'lx','age':'35','height':'170'}
y=x.copy()
y
{'name': 'lx', 'age': '35', 'height': '170'}####浅复制
采用替换副本中的值的方式原件不会收到影响,如果就地修改副本中的值原件也会修改
x={'name':'lx','age':'35','height':['170','180','190']}
x
{'name': 'lx', 'age': '35', 'height': ['170', '180', '190']}
y
{'name': 'xx', 'age': '35', 'height': '170'}
y=x.copy()
y
{'name': 'lx', 'age': '35', 'height': ['170', '180', '190']}
y['height'].remove('190')
y
{'name': 'lx', 'age': '35', 'height': ['170', '180']}
x
{'name': 'lx', 'age': '35', 'height': ['170', '180']}
y['name']='cc'
y
{'name': 'cc', 'age': '35', 'height': ['170', '180']}
x
{'name': 'lx', 'age': '35', 'height': ['170', '180']}

deepcopy:深复制,副本中修改不影响原件

from copy import deepcopy
d={}
d
{}
d['name']=['lx','cc']
d
{'name': ['lx', 'cc']}
c=d.copy()
c
{'name': ['lx', 'cc']}
dc=d.deepcopy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'deepcopy'
dc=deepcopy(d)
d['name'].append('dd')
c
{'name': ['lx', 'cc', 'dd']}
dc
{'name': ['lx', 'cc']}

fromkey:创建一个新dict,且其中的项都为none

dict.fromkeys(['name','age','height'])
{'name': None, 'age': None, 'height': None}

get:提供宽松的环境

c={}
print(c['name'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
print(c.get('name'))
c.get('name',N/A)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'N' is not defined
c.get('name','N/A')
'N/A'

修改一下上面写过的数据库
#__coding utf-8__
people={
'lx':{
'phone':'123',
'addr':'fdfsf'},
'sdy':{
'phone':'456',
'addr':'test'},
'sb':{
'phone':'789',
'addr':'test1'
}
}
labels={'phone':'phonenumber',
'addr':'address'
}
name=input('Name:')
r=input('Please input number(p) or address(a)')
key=r
if r=='p':key='phone'
if r=='a':key='addr'
person=people.get(name,{})
label=labels.get(key,key)
result=person.get(key,'No result')

print("{}'s {} is {}".format(name,label,result))

执行结果如下:
D:\work>python people.py
Name:cc
Please input number(p) or address(a)dd
cc's dd is No result

items:返回包含所有dict项的列表,每个元素为(key,value)的形式

返回值为一个字典视图,

d={'title':'header','long':'19'}
d.items()
dict_items([('title', 'header'), ('long', '19')])
d
{'title': 'header', 'long': '19'}
it=d.items()
it
dict_items([('title', 'header'), ('long', '19')])
('title','header') in it
True
len(it)
2
len(d.items())
2
list(it)
[('title', 'header'), ('long', '19')]

keys:返回一个字典视图,包含指定字典中的键

pop:获取指定键关联的值,并将该键-值对删除

d.pop('long')
'19'
d
{'title': 'header'}

popitem:随机删除dict中的项

setdefault:获取指定键关联值,如果键不存在会创建键对

c=d.setdefault('name')
c
d
{'name': None}
c
d
{'name': None}

update:使用dict中的一项更新另一个dict中的项

d={'name':'lx','age':'24','height':'190'}
x={'name':'sdy'}
d.update(x)
d
{'name': 'sdy', 'age': '24', 'height': '190'}

values:返回dict中的值,values可以有重复值

d={}
d[1]=1
d[2]=2
d[3]=1
d.values()
dict_values([1, 2, 1])

转载于:https://blog.51cto.com/13620507/2105118

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值