python学习之字典

#######字典######


1.为什么需要字典类型?
In [1]: list1 = ["name", "age", "class" ]

In [2]: list2 = ["lee", "12" , "math" ]

In [3]: zip(list1,list2)
Out[3]: [('name', 'lee'), ('age', '12'), ('class', 'math')]
            //通过zip内置函数将两个列表结合,help(zip)                

In [6]: list2[0]    //在直接编程时,并不能理解第一个索引表示姓名
Out[6]: 'lee'

In [8]: list2['name']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-0e1b97447f8e> in <module>()
----> 1 list2['name']

TypeError: list indices must be integers, not str


故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。
2.字典的定义
对字典的处理方法
In [6]: 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 [10]: dic = { "name":"lee","age":"10","class":"math" }

In [11]: dic["name"]
Out[11]: 'lee'

In [12]: dic['class']
Out[12]: 'math'

In [13]: dic[1]            ##不能用这种方法索引
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-13-3e9497c0fbd7> in <module>()
----> 1 dic[1]

KeyError: 1




• 内建方法:fromkeys
字典中的key有相同的value值,默认为None
In [14]: di = {}.fromkeys(('username','password'),'fentiao')

In [15]: di
Out[15]: {'password': 'fentiao', 'username': 'fentiao'}

In [16]: di1 = {}.fromkeys(('username','password'),)

In [17]: di1

Out[17]: {'password': None, 'username': None}



In [32]: dic.fromkeys([1,2,3,4])
Out[32]: {1: None, 2: None, 3: None, 4: None}

In [33]: dic.fromkeys([1,2,3,4],'hello')
Out[33]: {1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello'}

3.字典值的访问
•直接通过key访问
In [18]: dic
Out[18]: {'age': '10', 'class': 'math', 'name': 'lee'}

In [19]: dic['name']
Out[19]: 'lee'

In [20]: dic['class']
Out[20]: 'math'

In [21]: dic['age']
Out[21]: '10'

•循环遍历访问
In [22]: dic
Out[22]: {'age': '10', 'class': 'math', 'name': 'lee'}

In [23]: for key in dic:
   ....:     print dic[key]
   ....:     
10
lee

math



In [34]: dic
Out[34]: {'age': '10', 'class': 'math', 'name': 'lee'}

In [35]: for key in dic.keys():
   ....:     print "key=%s" % key
   ....:     
key=age
key=name
key=class

In [36]: for value in dic.values():
    print "value=%s" % value
   ....:     
value=10
value=lee
value=math



4.字典key-value的添加
•dic[key] = value
In [24]: dic['kind'] = 'cat'

In [25]: dic

Out[25]: {'age': '10', 'class': 'math', 'kind': 'cat', 'name': 'lee'}//通过这个操作,我们会发现字典是无序的数据类型



5.字典的更新
1)
In [4]:  dic = { "name":"lee","age":"10","class":"math" }

In [5]: dic1 = {"gender":"male"}

In [6]: dic.update(dic1)

In [7]: dic

Out[7]: {'age': '10', 'class': 'math', 'gender': 'male', 'name': 'lee'}



2)
In [8]: dic = {"home":"456","hello":"123"}

In [9]: dic1 = {"sisi":"123","home":"123"}

In [10]: dic.update(dic
dic   dic1  dict  

In [10]: dic.update(dic1)

In [11]: dic
Out[11]: {'hello': '123', 'home': '123', 'sisi': '123'}

6.字典的删除
•dic.clear()        //删除字典中的所有元素
In [11]: dic
Out[11]: {'hello': '123', 'home': '123', 'sisi': '123'}

In [12]: dic.c
dic.clear  dic.copy   

In [12]: dic.clear()

In [13]: dic

Out[13]: {}



•del(dic)        //删除字典本身字典的常用方法
In [14]: dic1
Out[14]: {'home': '123', 'sisi': '123'}

In [15]: del(dic1)

In [16]: dic1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-c95a6e8d4d0a> in <module>()
----> 1 dic1

NameError: name 'dic1' is not defined



• dic.pop(key)        //根据key值删除字典的元素;
In [19]: dic = { "name":"lee","age":"10","class":"math" }


In [21]: dic.pop("age")
Out[21]: '10'

In [22]: dic
Out[22]: {'class': 'math', 'name': 'lee'}

• dic.popitem()        //随机删除字典元素,返回(key,value)
In [22]: dic

Out[22]: {'class': 'math', 'name': 'lee'}



In [23]: dic.popitem()
Out[23]: ('name', 'lee')

In [24]: dic

Out[24]: {'class': 'math'}




• dic.keys()        //返回字典的所有key值
In [25]: dic = { "name":"lee","age":"10","class":"math" }

In [26]: dic
Out[26]: {'age': '10', 'class': 'math', 'name': 'lee'}

In [27]: dic.keys()
Out[27]: ['age', 'name', 'class']

In [28]: dic.values()
Out[28]: ['10', 'lee', 'math']

• dict.get()        //如果key存在于字典中,返回对应value值
In [29]: dic.get("age")

Out[29]: '10'




•dict.has_keys()    //字典中是否存在某个key值
In [30]: dic.has_key("age")
Out[30]: True

In [31]: dic.has_key("dddd")

Out[31]: False




7.
In [11]: dic
Out[11]: {'age': '10', 'class': 'math', 'name': 'lee'}

In [12]: for k,v in dic.items():
   ....:     print "%s -> %s" %(k,v)
   ....:     
age -> 10
name -> lee
class -> math
8.小总结
此处的有序无序是指内部的存放顺序与元素的放入顺序是否有关
字符串:
    书写方式:'' "" """ """ ''' '''
        不可变数据类型
        有序
列表:
    书写方式:[]
        可变数据类型
        有序序列
元组:
    书写方式:()
        不可变数据类型
        有序序列
集合:
    书写方式:{1,2}
        可变数据类型
        无序
字典:
    书写方式:{"name":"hello"}
        可变数据类型
        无序


9.列表的应用

In [14]: data = ['fentiao','50','1000',(2017,12,3)]

In [15]: name, shares, juankuan, date = data

In [16]: print name,shares, juankuan, date
fentiao 50 1000 (2017, 12, 3)

In [18]: print name,juankuan
fentiao 1000

In [19]: _,shares, _,date = data

In [20]: print shares,date
50 (2017, 12, 3)

In [21]:

对一组数据去掉最大和i最小值然后求平均值

In [25]: import heapq

In [26]: li = [90,91,97,99,94,95]

In [27]: print heapq.nlargest(1,li)
[99]

In [28]: li.sort()            //先排序

In [29]: li
Out[29]: [90, 91, 94, 95, 97, 99]

In [30]: li.pop(0)            //删除最小值
Out[30]: 90

In [31]: li.pop(len(li)-1)        //删除最大值
Out[31]: 99

In [32]: sum(li)/len(li)        //求平均值
Out[32]: 94

In [33]:



10.用字典写四则运算
#!/usr/bin/env python
# coding:utf-8
from __future__ import division
'''
@author:houruiyun
@file:2.py
@contact:674211605.qq.com
@time:6/25/172:45 AM
@desc:
'''
num1 = input('input num1:')
oper = raw_input('act:')
num2 = input('input num2:')
dic = {'+':num1+num2, '-':num1-num2, '*':num1*num2, '/':num1/num2}
if oper in dic.keys():
    print dic[oper]



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值