笔记:
1、字典是Python中唯一的映射类型
2、字典包含两个要素:键(key)和值(value)他们是成对出现的,用大括号括起来,多对存在时用逗号隔开。
3、改变字典中的某个值:dict2[key] = ‘value’,插入的方法类似
一、使用dict()函数创建字典
第一种:创建空字典
>>> dict1=dict()
>>> dict1
{}
第二种:关键字参数
dict2 = dict(key1 = value1,key2 = value2),则最后的形式为:
dict2 = {key2:value2,key1:value1}Python的dict是无序的。
>>> dict2 = dict(one = 1,two = 2,three = 3)
>>> dict2
{'one': 1, 'two': 2, 'three': 3}
!!!!!!!!!!!!!注意以下方法会出错:
>>> dic2 = dict(1 = "one",2 = "two",3 = "three")
SyntaxError: invalid syntax
第三种:dict(list)
>>> list1 = [(1,"one"),(2,"two"),(3,"three")]
>>> dict3 = dict(list1)
>>> dict3
{1: 'one', 2: 'two', 3: 'three'}
第四种:dict(tuple)
可以用dict()直接创建字典,如dict1 = dict(((‘F’,70),(‘i’,105),(’s’,115),(‘h’,104),(‘C’,67))),创建出来的字典dict1的形式为{(‘F’,70),(‘i’,105),(’s’,115),(‘h’,104),(‘C’,67)}
>>> tup = ((1,"one"),(2,"two"),(3,"three"))
>>> dict4 = dict(tup)
>>> dict4
{1: 'one', 2: 'two', 3: 'three'}
第五种:dict(zip())
>>> t = zip([1,2,3,],[4,5,6,])
>>> t
<zip object at 0x0000000002FD4788>
>>> list(t)
[(1, 4), (2, 5), (3, 6)]
>>> dict5 = dict(t)
>>> dict5
{}
>>> dict5 = dict(zip([1,2,3,],[4,5,6,]))
>>> dict5
{1: 4, 2: 5, 3: 6}
第六种:dict.fromkeys( list , var )
注意第二个参数var,只能是一个变量
>>> dict.fromkeys(range(3),9)
{0: 9, 1: 9, 2: 9}
>>> dict.fromkeys(range(1,3),["one","two",])
{1: ['one', 'two'], 2: ['one', 'two']}
注意zip()函数:
>>> t = zip([1,2,3,],[4,5,6,])
>>> t
<zip object at 0x0000000002FD4788>
>>> list(t)
[(1, 4), (2, 5), (3, 6)]
二、一些常用方法
0. keys() \ values()\items()
略
1.copy()
>>> d = dict(zip([1,2,3],["one","two","three"]))
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> temp1 = d.copy()
>>> temp1
{1: 'one', 2: 'two', 3: 'three'}
>>> temp2 = d
>>> temp2
{1: 'one', 2: 'two', 3: 'three'}
>>> id(d)
50135256
>>> id(temp1)
50212656
>>> id(temp2)
50135256
2.clear()
>>> d = dict(zip([1,2,3],["one","two","three"]))
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> temp1 = d.copy()
>>> temp2 = d
>>> temp2.clear()
>>> temp2
{}
>>> temp1
{1: 'one', 2: 'two', 3: 'three'}
3.get(key)———->value
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> d.get(2)
'two'
4.pop(key)
>>> d.pop(2)
'two'
>>> d
{1: 'one', 3: 'three'}
5.popitem()
>>> d
{1: 'one', 3: 'three'}
>>> d.popitem()
(3, 'three')
6.update()
>>> d
{1: 'one', 3: 'three'}
>>> d.popitem()
(3, 'three')
>>> c = {2:"two"}
>>> d.update(c)
>>> d
{1: 'one', 2: 'two'}