- 字典: 单词:键(key)、
单词的含义:值(value)
访问字典中的值:
>>> math={'1':'一','2':'二','3': '三'}
>>> print(math['1'])
一
空字典:dic1={}
添加字典的键-值对:
>>> math={'1':'一','2':'二','3': '三'}
>>> math['4']='四'
>>> math['5']='五'
>>> print(math)
{'1': '一', '2': '二', '3': '三', '4': '四', '5': '五'}
修改字典中的值:
>>> math={'1':'一','2':'二','3': '三'}
>>> math['4']='五'
>>> print(math)
{'1': '一', '2': '二', '3': '三', '4': '五'}
删除键-对值:
>>> math={'1':'一','2':'二','3': '三'}
>>> del math[‘1’]
>>> print(math)
{'2': '二', '3': '三', '4': '四'}
dict()函数:
>>> math=dict((('一',1),('二',2)))
>>> math
{'一': 1, '二': 2}
(也可用列表构建键-值对)
>>> math=dict(一='1',二='2')
>>> math
{'一': '1', '二': '2'}
(一、 二不能用‘’,因为其为变量名)
fromkeys():
>>> dict1={}
>>> dict1.fromkeys((1,2,3),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
key()函数:
>>> dict1=dict1.fromkeys((1,2,3),'number')
>>> for each in dict1.keys():
print (each)
1
2
3
values()函数:
>>> dict1=dict1.fromkeys((1,2,3),'number')
>>> for each in dict1.values():
print(each)
number
number
number
items()函数:
>>> dict1=dict1.fromkeys((1,2,3),'number')
>>> for each in dict1.items():
print(each)
(1, 'number')
(2, 'number')
(3, 'number')
get()函数:
>>> dict1=dict1.fromkeys((1,2,3),'number')
>>> for each in dict1.items():
print(each)
(1, 'number')
(2, 'number')
(3, 'number')
>>> dict1.get(4)
>>> print(dict1.get(4))
None
>>> dict1.get(4,"该字典内无该索引")
'该字典内无该索引'
>>> dict1.get(2,"该字典内无该索引")
'number'
成员操作符在字典中应用:(查找该索引是否在字典中存在)
>>> 4 in dict1
False
>>> 2 in dict1
True
clear()函数:清空字典
>>> dict1.clear()
>>> dict1
{}
copy()语句:与赋值语句不同,给拷贝字典分配新地址。
>>> a={1:'one',2:'two',3:'three'}
>>> b=a.copy()
>>> c=a
>>> c
{1: 'one', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
2337255629952
>>> id(c)
2337255629952
>>> id(b)
2337256038272
>>> a[4]='four'
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
pop()语句:
>>> a={1:'one',2:'two',3:'three', 4: 'four'}
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three', 4: 'four'}
popitem()语句:括号内不能指定索引,弹出字典内最后一个键-值。
>>> a={1:'one',2:'two',3:'three', 4: 'four'}
>>> a.popitem()
(4, 'four')
>>> a
{1: 'one', ,2:'two', 3: 'three'}
setdefault()语句:
>>> a={1:'one',2:'two',3:'three', 4: 'four'}
>>> a.setdefault(5)
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None}
>>> a.setdefault(6,'six')
'six'
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None, 6: 'six'}
update()语句:更新字典
>>> a={1:'one',2:'two',3:'three', 4: 'four'}
>>> b={5:'five'}
>>> a.update(b)
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}