字典创建
>>>a={‘a’:’animal’,’b’:’human’}
用内置函数dict()快速创建字典
>>> keys=['a','b','c','d']
>>> values=[1,2,3,4]
>>> adict=dict(zip(x,y))
>>> print(adict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> adict=dict(name='wang',age='22')
>>> adict
{'name': 'wang', 'age': '22'}
字典元素增加,修改
>>> keys=['name','sex','age']
>>> values=['hua','male','21']
>>> d=dict(zip(keys,values))
>>> d
{'name': 'hua', 'sex': 'male', 'age': '21'}
>>> d['age']=99
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99}
>>> d['address']='hubei'
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei'}
update()函数
>> d
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei'}
>>> d.update({'age':22,'q':11})
d
{'name': 'hua', 'sex': 'male', 'age': 22, 'address': 'hubei', 'q': 11}
del删除命令
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei', 'q': 11}
>>> d
{'name': 'hua', 'sex': 'male', 'age': 99, 'address': 'hubei', 'q': 11}
>>> del d['age']
>>> d
{'name': 'hua', 'sex': 'male', 'address': 'hubei', 'q': 11}
>>> del d
>>> d
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
d
NameError: name 'd' is not defined
setdefault(键,值 )
存在则返回,不存在则创建
>>> adict.setdefault('address','beijing')
'beijing'
>>> adict
{'age': 22, 'name': 'huaqiao', 'sex': 'male', 'address': 'beijing'}
>>>
字典的遍历
当对字典遍历输出时,默认输出字典的键
>>> for i in adict:
print(i)
age
name
sex
address
>>>
items()返回字典的键值
>>> for i in adict.items():
print(i)
('age', 22)
('name', 'huaqiao')
('sex', 'male')
('address', 'beijing')
>>>
items(),keys(),values()
>>> adict.items()
dict_items([('age', 22), ('name', 'huaqiao'), ('sex', 'male'), ('address', 'beijing')])
>>> adict.keys()
dict_keys(['age', 'name', 'sex', 'address'])
>>> adict.values()
dict_values([22, 'huaqiao', 'male', 'beijing'])
>>>
集合set
和字典一样用大括号{}作为界定符,元素唯一,不可重复。
集合创建:“=”
>>> q={1,2,3,4,5}
>>> q
{1, 2, 3, 4, 5}
>>>
Set转换
>>> a=set([1,2,3,4,5])
>>> a
{1, 2, 3, 4, 5}
>>>
集合元素增加add(),update( )
>>> k={1,2,3,4}
>>> k.add(999)
>>> k
{1, 2, 3, 4, 999}
>>> b={111,222}
>>> k.update(b)
>>> k
{1, 2, 3, 4, 999, 111, 222}
集合元素删除
pop(x):删除并返回最左边的一个元素
remove(要删除的元素):
discard(要删除的元素):
clear():
集合运算
>>> a={1,2,3}
>>> b={3,4,5,6}
>>> a|b #并集
{1, 2, 3, 4, 5, 6}
>>> a&b #交集
{3}
>>> a-b #差集
{1, 2}
>>>
>>> a.symmetric_difference(b)
{1, 2, 4, 5, 6} #对称差集