Python学习笔记-字典和集合

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})
各种内置方法
  1. fromkeys()创建并返回一个新字典
>>> dict.fromkeys((1,2,3) , ("one", "two", "three"))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
  1. key()用于返回字典中的键,values() 用于返回字典中的所有值、items() 返回所有键值对
  2. get(键值)可以得到对应的值,如果没有,返回None
  3. clear() 清空内容
  4. in 或者 not in 可以判断一个键是否在字典中
  5. copy() 复制字典
  6. pop() 弹出对应的值,popitem() 弹出一个项
>>>a=dict.fromkeys((1,2,3) , ("one", "two", "three"))
>>>a
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> a.pop(2)
('one', 'two', 'three')
>>> a
{1: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> a.popitem()
(3, ('one', 'two', 'three'))
>>> a
{1: ('one', 'two', 'three')}
>>>
>>> a = {"白":'白',"xiao":'白',"小白":'白'} # 更新字典
>>> a.update(小白= '5')
>>> 5

2、集合

你可能感兴趣的:(Python学习笔记-字典和集合)