# @Time : 2017/7/6 20:36
# @Author : 原创作者:谷哥的小弟
# @Site : 博客地址:http://blog.csdn.net/lfdfhl
# @DESC : Dictionary
'''
字典的每个元素由两部分组成即键和值
可依据键查询其对应的值,如person['name']获取name对应的值
亦可使用get()方法,假若该键不存在则返回默认值
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
print('name=',person['name'])
print('age=',person['age'])
print('address=',person['address'])
gender=person.get('gender','男')
print('gender=',gender)
print('= '*20)
'''
利用items()即可获取字典所有元素
利用keys()获取字典中的所有key
利用values()获取字典中的所有value
利用in判断key是否在字典中;如果在则返回True,否则返回False
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
items=person.items();
for item in items:
print('字典中的item=',item)
keys=person.keys()
for key in keys:
print('字典中的key=',key)
values=person.values()
for value in values:
print('字典中的value=',value)
result='gen' in person
print('result=',result)
print('= '*20)
'''
利用len()获取字典中元素个数
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
count=len(person)
print('count=',count)
print('= '*20)
'''
修改字典中的元素的值
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
person['age']=27
print('修改后的age=%i'%person['age'])
print('= '*20)
'''
往字典中添加元素
示例如下:
往字典中添加gender=male
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
person['gender']='male'
gender=person['gender']
print('gender=',gender)
print('= '*20)
'''
删除字典中的元素
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
del person['address']
items=person.items();
for item in items:
print(item)
print('= '*20)
'''
利用clear()清空字典
'''
person={'name':'谷哥的小弟','age':25,'address':'china'}
person.clear()
count=len(person)
print('清空后字典中元素个数=',count)
print('= '*20)
结果如下:
name= 谷哥的小弟
age= 25
address= china
gender= 男
= = = = = = = = = = = = = = = = = = = =
字典中的item= ('name', '谷哥的小弟')
字典中的item= ('age', 25)
字典中的item= ('address', 'china')
字典中的key= name
字典中的key= age
字典中的key= address
字典中的value= 谷哥的小弟
字典中的value= 25
字典中的value= china
result= False
= = = = = = = = = = = = = = = = = = = =
count= 3
= = = = = = = = = = = = = = = = = = = =
修改后的age=27
= = = = = = = = = = = = = = = = = = = =
gender= male
= = = = = = = = = = = = = = = = = = = =
('name', '谷哥的小弟')
('age', 25)
= = = = = = = = = = = = = = = = = = = =
清空后字典中元素个数= 0
= = = = = = = = = = = = = = = = = = = =