大鹏

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

字典

 本章节主要内容:

  1、映射类型
  2、创建字典
      2.1创建字典的五种方式
  3、访问字典
  4、各种内置的方法
    4.1 fromkeys()
    4.2、keys(),values()和items()
    4.3 get()
    4.4 clear()
    4.5 copy()
    4.6、pop() 和popitem()
    4.7 setdefault()
    4.8 update()
  5、收集参数
  6、作业

  7、参考

 

 字典

 

1、映射类型

字典是Python中唯一的映射类型,映射是数学上的一个术语。指两个元素集之间元素相互“对应”的关系。

#建立映射关系
brand = ['李宁','耐克','阿迪达斯','鱼C工作室']
slogan = ['一切皆有可能','Just do it','Impossible is nothing','让编程改变世界']

l = brand.index('鱼C工作室') #集合没有序列,这个是错误的
print("鱼C工作室的口号是:",slogan[l])

 

 

2、创建字典

字典有自己标志性符号大括号({})来定义。字典由多个键及其对应的值来共同构成,每一对键值组合称为项。

字典的键必须是独一无二的,而值可以取任何数据类型,但必须是不可变的(如字符串、数或者元组)

#声明一个空字典
empty = {}
print(empty)         # {}
print(type(empty))    # <class 'dict'>

 

#方式一、创建字典
dict1 = {'李宁':'一切皆有可能','耐克':'Just do it','阿迪达斯':'Impossible is nothing','鱼C工作室':'让编程改变世界'}
print(dict1)
#{'李宁': '一切皆有可能', '耐克': 'Just do it', '阿迪达斯': 'Impossible is nothing', '鱼C工作室': '让编程改变世界'}

 

#方式二:使用dict()来创建字典
dict1 = dict((('F',70),('i',105),('s',115),('h',104),('c',67))) print(dict1)
dict3=dict((('f',70),)) #这里一定要有个逗号,
# {'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}

#上面的方式括号太多,我们改进为下面的 dict1 = dict(F = 70,i = 105,s =115,h = 104,c =67) #注意键的位置不能加上字符串的引号,否则会报错 #错误的方式 dict1 = dict('F' = 70,'i' = 105,'s' =115,'h' = 104,'c'=67) #报错 SyntaxError: keyword can't be an expression

 

#方式三、直接给字典的键赋值的方式来创建字典

dict1 = {'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}

#通过直接给字典的键赋值的方式来创建字典,如果键存在,则修改键对应的值,如果不存在,则创建一个新的键并赋值
dict1['x'] = 88    #创建一个新的键‘x',并赋值88
dict1['y'] = 88    #创建一个新的键‘y',并赋值88
print(dict1)    #{'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67, 'x': 88, 'y': 88}

dict1['x'] = 120   #修改键‘x'的值为120
print(dict1)    #{'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67, 'x': 120, 'y': 88}

 

#这种方式最常用,使用赋值的方式
dict1={}
dict1['0']='A'

这种代码里经常用

 

 

2.1创建字典的五种方式:

a = dict(one =1,two=2,three=3)
b = {'one':1,'two':2,'three':3}
c = dict(zip(['one','two','three'],[1,2,3]))
d = dict([('two',2),('one',1),('three',3)])
e = dict({'three':3,'one':1,'two':2})

print(a)
print(b)
print(c)
print(d)
print(e)


"""
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'two': 2, 'one': 1, 'three': 3}
{'three': 3, 'one': 1, 'two': 2}

"""

 

 

3、访问字典

 字典是通过key来取值的,这个列表通过索引来取值有区别

 

dict1 = {'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}

print(dict1['F'])    # 70   #通过key来取值

dict1['i'] = 120     #修改‘i'的值为 120
print(dict1)

#获取所有的键
print(dict1.keys())    # dict_keys(['F', 'i', 's', 'h', 'c'])
# 获取所有的值
print(dict1.values())  # dict_values([70, 120, 115, 104, 67])
#获取所有的键值对
print(dict1.items())   # dict_items([('F', 70), ('i', 120), ('s', 115), ('h', 104), ('c', 67)])

 

循环dict 取值

#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用  #这个方法很好,记住
    print(k,v)
    


dict1 = {'F': 70, 'i': 105, 's': 115, 'h': 104, 'c': 67}
for i ,j in dict1.items():
    print(i,j)

'''
结果:
F 70
i 105
s 115
h 104
c 67

'''

 

 

 

4、各种内置的方法

 要点:通过dir(dict)查出所有的内置函数,再通过help(dict)查看帮助文档 ,并可以查看具体的使用方法,如help(dict.clear),help(dict.keys)的帮助文档

 

for each in dir(dict):
    print(each)

"""
clear
copy
fromkeys
get
items
keys
pop
popitem
setdefault
update
values
"""

 

help(dict)

 dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)

 

4.1 fromkeys()

fromkeys()方法用于创建并返回一个新的字典,它有两个参数,第一个参数是字典的键,第二个参数是可选的,是传入键对应的值。如果不提供,默认为None。

dict1 = {}
a = dict1.fromkeys((1,2,3))   #不传入参数
print(a)   # {1: None, 2: None, 3: None}

dict2 = {}
b = dict2.fromkeys((1,2,3),'number')  #传入一个参数number
print(b)   # {1: 'number', 2: 'number', 3: 'number'}

#可以直接使用dict
b =dict.fromkeys((1,2,3),'number')
dict3 = {} c = dict3.fromkeys((1,2,3),('one','two','three')) #传入一个元组 print(c) # {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')} #注意:fromkeys() 把('one','two','three') 当成一个值

 

4.2、keys(),values()和items()

访问字典的方法有keys(),values()和items()

keys() 用于返回字典中的键,values()用于返回字典中所有的值,items() 用于返回字典中所有的键值对(也就是项)

dict1 = {}
dict1 = dict1.fromkeys(range(32),'')
print(dict1)
a =  dict1.keys()
print(a)   #dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, ......])

b = dict1.values()
print(b)   #ict_values(['赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞'.......])

c =  dict1.items()
print(c)   #dict_items([(0, '赞'), (1, '赞'), (2, '赞'), (3, '赞'), (4, '赞'), (5, '赞'), ......)


#通过key来取值
print(dict1[31])

print(dict1[32])   #键不存在会报错,KeyError: 32

 

4.3 get()

#使用get()取值
print
(dict1.get(31)) #存在 print(dict1.get(32)) #不存在返回None,不会报错

 

#使用成员资格操作符(in 或者 not in) ,在字典中检查键的成员资格比序列更高效
#因为字典是采用哈希的方法一对一找到成员,而序列则是采取迭代的方式逐个比对
dict1 = dict.fromkeys(range(32),'')
print(dict1)
print(31 in dict1)    # True
print(32 in dict1)    #False

 

4.4 clear()

clear() 清空一个字典

dict1 = {}
dict1 = dict1.fromkeys(range(32),'')

dict1.clear()    #清空字典
print(dict1) 

 

4.5 copy()

copy()方法是复制字典

a = {1:'one',2:'two',3:'three'}
b = a.copy()
print(b)       # {1: 'one', 2: 'two', 3: 'three'}

print(id(b))   # 31935008
a[1] = 'four'
print(a)       # {1: 'four', 2: 'two', 3: 'three'}
print(b)       # {1: 'one', 2: 'two', 3: 'three'}

 

4.6、pop() 和popitem()

pop() 是给定键弹出对应的值,popitem()是弹出一个项

a = {1:'one',2:'two',3:'three',4:'four'}
print(a.pop(2))         #  two
print(a)                #  {1: 'one', 3: 'three', 4: 'four'}

print(a.popitem())      # (4, 'four')  默认弹出最后一个
print(a)                # {1: 'one', 3: 'three'}

 

4.7 setdefault()

setdefault() 方法和get()方法有点类似。setdefault()在字典中找不到相应的键时会自动添加

#找不到对应的键,会自动添加
a = {1:'one',2:'two',3:'three',4:'four'}
print(a.setdefault(3))     # three
print(a.setdefault(5))    # None
print(a)               # {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None}

 

#利用setdefault解决重复赋值
'''
setdefault的功能
1:key存在,则不赋值,key不存在则设置默认值
2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值
d={}
print(d.setdefault('a',1)) #返回1

d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
    print(dic)

 

 

4.8 update()

update() 方法是用于更新字典

pets = {'米老鼠':'老鼠','汤姆':'',"小白":''}
pets.update( 小白 = "")
print(pets)

 

 

 

5、收集参数

 使用两个(**),两个星号的收集参数表示为将参数们打包成字典的形式。

收集参数有两种打包方式:一种是以元组的形式打包;另一种则是以字典的形式打包

def test(** params):
    print("有%d个参数" % len(params))
    print("它们分别是:",params)

test(a =1,b= 2,c =3,d =4 ,e =5)
#当参数带两个星号(**)时,传递给函数的任意个key =value实参会被打包进一个字典中

"""
运行结果:
有5个参数
它们分别是: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
"""

a = {'one':1,'two':2,'three':3}
#解包
test(**a)

"""
运行结果:
有3个参数
它们分别是: {'one': 1, 'two': 2, 'three': 3}
"""

 

 

 

6、作业

[课后作业] 第025讲:字典:当索引不好用时 | 课后测试题

[课后作业] 第026讲:字典:当索引不好用时2 | 课后测试题

 

 

7、参考

https://www.cnblogs.com/hcxy2007107708/articles/9978136.html#_labe16

https://www.cnblogs.com/alex3714/articles/5717620.html

http://www.cnblogs.com/wupeiqi/articles/5444685.html

腾讯课堂——基础数据类型(dict字典)

 

posted on 2018-12-15 19:31  pf42280  阅读(350)  评论(0)    收藏  举报