定义
字典是无序数据类型,不支持索引、切片
字典里的key不能重复,但是value没有任何限制
创建
简单字典创建:
In [44]: dic={"name":"tom","age":10,"gender":"male"}
In [45]: dic["name"]
Out[45]: 'tom'
使用工厂函数创建:
In [46]: dic=dict(a=1,b=2)
In [47]: dic
Out[47]: {'a': 1, 'b': 2}
内建方法:fromkeys
字典中的key有相同的value值默认为None,也可以手动设置
In [48]: dic={}.fromkeys(('username','password'),'redhat')
In [49]: dic
Out[49]: {'password': 'redhat', 'username': 'redhat'}
In [50]: dic={}.fromkeys(('username','password'),)
In [51]: dic
Out[51]: {'password': None, 'username': None}
In [52]: d={}
In [53]: d.fromkeys(range(1,10),"0000")
Out[53]:
{1: '0000',
2: '0000',
3: '0000',
4: '0000',
5: '0000',
6: '0000',
7: '0000',
8: '0000',
9: '0000'}
练习1:
生成100个学号,学号总共由7位数组成,前两位“14”开头,代表学校编号;
请生成学号1400001~1400100
#!/usr/bin/env python
# coding:utf-8
stu_ids = []
for i in range(1,101):
s_id = "1400%.3d" %(i) #将i以3位数打印出来,并且在i前面加上1400
stu_ids.append(s_id)
print stu_ids
执行结果:
字典的访问
直接通过key访问:
In [55]: dic={'name':'tom','age':10,'gender':'male'}
In [56]: dic['name']
Out[56]: 'tom'
循环遍历访问:
- 遍历打印key
In [59]: dic={'name':'tom','age':10,'gender':'male'}
In [60]: for k in dic:
print k
....:
gender
age
name
- 遍历打印value
In [57]: dic={'name':'tom','age':10,'gender':'male'}
In [58]: for k in dic:
....: print dic[k]
....:
male
10
tom
字典key-value的添加
dic[key] = value
通过这个操作,我们会发现字典是无序的数据类型
In [61]: dic={'name':'tom','age':10,'gender':'male'}
In [62]: dic['kind']='cat'
In [63]: dic
Out[63]: {'age': 10, 'gender': 'male', 'kind': 'cat', 'name': 'tom'}
字典的修改
In [68]: dic={'name':'tom','age':10,'gender':'male'}
In [69]: dic['name']='jack'
In [70]: dic
Out[70]: {'age': 10, 'gender': 'male', 'name': 'jack'}
字典的删除
dic.pop(key)根据key值删除字典的元素;dic.popitem()随机删除字典元素,返回(key,value)dic.clear()
删除字典中的所有元素del dic
删除字典本身
字典的常用方法
dict.get()如果key存在于字典中,返回对应value值dic.keys()返回字典的所有key值dict.has_keys()字典中是否存在某个key值
其他: