1. 为什么需要字典类型?
>>> list1 = ["name", "age", "gender"]
>>> list2 = ["fentiao", 5, "male"]
>>> zip(list1, list2) //通过zip内置函数将两个列表结合,help(zip)
[('name', 'fentiao'), ('age', 5), ('gender', 'male')]
>>> list2[0] //在直接编程时,并不能理解第一个索引表示姓名
'fentiao'
>>> list2[name]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。
2.字典的定义
In [8]: dic = {"name":"linux","age":22} #######定义一个字典
In [10]: dic["name"] //根据key找出value值,不能通过索引寻找value值
Out[10]: 'linux'
In [11]: dic["age"]
Out[11]: 22
In [12]: user = ['westos','linux'] ##########定义列表
In [13]: passwd=['redhat','blue']
In [14]: zip(user,passwd) //通过zip内置函数将两个列表结合,help(zip
Out[14]: [('westos', 'redhat'), ('linux', 'blue')]
""""""
""""""
In [15]: dic={'westos':'redhat','linux':'blue'}
In [16]: dic['westos'] //根据key找出value值
Out[16]: 'redhat'
In [17]: dic['westos'] =='redhat' 判断key对应的value值字典中知否存在?存在返回Ture
Out[17]: True
3. 字典的添加:
In [18]: dic={'westos':'redhat','linux':'blue'}
In [19]: dic['xiaobai']='123' ####key值和value值都不一样,整个添加。
In [20]: dic
Out[20]: {'linux': 'blue', 'westos': 'redhat', 'xiaobai': '123'}
In [21]: dic['linux']='block' ########key值一样和value值都不一样;将key对应的value值更新。
In [22]: dic
Out[22]: {'linux': 'block', 'westos': 'redhat', 'xiaobai': '123'}
4. 字典的常用命令
In [23]: dic={'westos':'redhat'}
In [24]: dic1={'linux':'blue'}
In [25]: dic.
dic.clear dic.items dic.pop dic.viewitems
dic.copy dic.iteritems dic.popitem dic.viewkeys
dic.fromkeys dic.iterkeys dic.setdefault dic.viewvalues
dic.get dic.itervalues dic.update
dic.has_key dic.keys dic.values
In [25]: dic.update(dic1)#######添加更新,####key值和value值都不一样,整个添加
In [26]: dic
Out[26]: {'linux': 'blue', 'westos': 'redhat'}
In [27]: dic={'westos':'redhat'}
In [28]: dic1={'westos':'blue'}
In [29]: dic.update(dic1) #### ##key值一样value值不一样;将key对应的value值更新
In [30]: dic
Out[30]: {'westos': 'blue'}
因为字典是无序的,所以没有索引和切片。
In [31]: dic={'westos':'redhat','linux':'blue'}
In [32]: dic.pop('westos') #####删除,必须加key值;
Out[32]: 'redhat' #####弹出字典中key值为"westos"的元素并返回该key的元素
In [33]: dic
Out[33]: {'linux': 'blue'}
In [35]: dic={'westos':'redhat','linux':'blue'}
In [36]: dic.popitem() #####删除,不加key值,随机删除
Out[36]: ('westos', 'redhat')
In [37]: dic
Out[37]: {'linux': 'blue'}
In [38]: dic.popitem()
Out[38]: ('linux', 'blue')
In [39]: dic
Out[39]: {}
In [40]: dic.popitem() ####key值删除完了,再删会报错
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-40-b472158de449> in <module>()
----> 1 dic.popitem()
KeyError: 'popitem(): dictionary is empty'
>>> dic.clear() //删除字典的所有元素
>>> dic
>>> del dic //删除整个字典
>>> dic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dic' is not defined
##########################################################
In [47]: dic={'westos':'redhat','linux':'blue'}
In [48]: dic.values() ##显示value值
Out[48]: ['redhat', 'blue']
In [49]: dic.keys() ##显示key值
Out[49]: ['westos', 'linux']
In [50]: dic.get("westos") ##查看key值对应的value值(有)
Out[50]: 'redhat'
In [51]: dic.get("hello") ##查看key值对应的value值(没有的情况下,返回值为none)
In [52]: print dic.get("hello")
None
In [53]: dic.has_key("hello") ##查看key值存在否?不存在显示False
Out[53]: False
In [54]: dic.has_key("linux") ##查看key值存在否?存在显示 True
Out[54]: True
>> ddict = {}.fromkeys(('username','password'),'fentiao')
//字典中的key有相同的value值,默认为None
>>> ddict
{'username': 'fentiao', 'password': 'fentiao'}
>>> ddict = {}.fromkeys(('username','password'),)
>>> ddict
{'username': None, 'password': None}
5.字典的去重功能
In [57]: dic.fromkeys('westos')
Out[57]: {'e': None, 'o': None, 's': None, 't': None, 'w': None}
In [58]: dic.fromkeys('westos','hello')
Out[58]: {'e': 'hello', 'o': 'hello', 's': 'hello', 't': 'hello', 'w': 'hello'}
In [59]: dic = {'westos':'redhat','westos':'234'}
In [60]: dic
Out[60]: {'westos': '234'}
6.访问字典的值:直接通过key访问,循环遍历字典的遍历
In [78]: for key in dic.keys(): ## 建立函数dic.keys()
....: print "key=%s" % key
....:
key=1
key=2
In [79]: for value in dic.values():## 建立函数 dic.values()
....: print "value=%s" % value
....:
value=a
value=2
In [81]: for key, value in dic.keys(), dic.values():##### 建立dic.keys()和 dic.values()函数
print "%s -> %s" %(key,value)
....:
1 -> 2
a -> 2
In [83]: dic.items()
Out[83]: [(1, 'a'), (2, '2')]
In [86]: for k,v in dic.items():
print "%s = %s" %(k,v)
....:
1 = a
2 = 2
7. 嵌套赋值
eg1:
对列表li = [34,45,32,132,43,55,],排序,去除最大值,最小值,求平均值。
In [106]: li = [34,45,32,132,43,55,]
In [107]: li.sort()
In [108]: li
Out[108]: [32, 34, 43, 45, 55, 132]
In [109]: li.pop(0)
Out[109]: 32
In [110]: li.pop(len(li)-1)
Out[110]: 132
In [111]: li
Out[111]: [34, 43, 45, 55]
In [112]: sum(li)/len(li)
Out[112]: 44
eg2:
四则运算:
from __future__ import division
number1 = input("num1=")
operate = raw_input("operate=")
number2 = input("num2=")
dic ={"+":number1+number2,"-":number1-number2,"*":number1*number2,"/":number1/number2}
if operate in dic.keys():
print dic[operate]