学习python的字典
前言
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割
dict = {‘a’: 1, ‘b’: 2, ‘b’: ‘3’}
dict.clear()
dict.copy()
dict.get(key, default=None)
dict.items()
dict.update(dict2)
dict.keys()
dict.values()
pop(key[,default])
popitem()
返回并删除字典中的最后一对键和值。
一、访问元素
放入对应的key和value:
student = {'name': 'jack', 'age': 5, 'class': 'one'}
print "student ['name']: ", student ['name']
print "student ['age']: ", student ['age']
输出结果:
dict['name']: jack
dict['age']: 5
二、修改元素
修改对应的key和value:
student = {'name': 'jack', 'age': 5, 'class': 'one'}
student ['age'] = 10 # 更新
student ['school'] = "rookie" # 添加
print "student ['age']: ", student ['age']
print "student ['school']: ", student ['school']
以上实例输出结果:
student [‘age’]: 10
student [‘school’]: rookie
二、删除元素
删除和清空:
student = {'name': 'jack', 'age': 5, 'class': 'one'}
print "student ['age']: ", student ['age']
print "student ['school']: ", student ['school']
需要逐一实现
del student['name']
student.clear()
del student