Python學習筆記-字典和集合

1、字典

創(chuàng)建的方法
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()創(chuàng)建并返回一個新字典
>>> 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、集合

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容