1. 程式人生 > >python--15 字典:當索引不好用

python--15 字典:當索引不好用

not with nothing get items span draw word mos

字典是python唯一的影射類型 hash

  >>> brand = [‘李寧‘, ‘耐克‘, ‘阿迪達斯‘]
  >>> slogan = [‘一切皆有可能‘, ‘Just do it‘,‘Impossible is nothing‘]
  >>> print(‘李寧的口號是:‘,slogan[brand.index(‘李寧‘)])
  李寧的口號是: 一切皆有可能

 字典不是序列類型 ,是映射類型

 字符串 列表 元組是序列類型

創建和訪問索引 標誌性符號--花括號

  創建字典方式一:key value

  >>> dict1 = {‘李寧‘:‘一切皆有可能‘,‘耐克‘:‘Just do it‘, ‘阿迪達斯‘:‘Impossible is nothing‘}


  >>> dict1
  {‘李寧‘: ‘一切皆有可能‘, ‘耐克‘: ‘Just do it‘, ‘阿迪達斯‘: ‘Impossible is nothing‘}
  >>> print(‘耐克口號是:‘, dict1[‘耐克‘])
  耐克口號是: Just do it

  >>> dict2 = {1:‘one‘,2:‘two‘,3:‘three‘}
  >>> dict2[3]
  ‘three‘

  創建空字典
  >>> dict3 = {}
  >>> dict3
  {}
  >>> dict3 = dict()


  >>> dict3
  {}

  通過dict()創建

  >>> help(dict)

  class dict(object)
  | dict() -> new empty dictionary
  | dict(mapping) -> new dictionary initialized from a mapping object‘s
  | (key, value) pairs
  | dict(iterable) -> new dictionary initialized as if via:
  | d = {}
  | for k, v in iterable:
  | d[k] = v
  | dict(**kwargs) -> new dictionary initialized with the name=value pairs
  | in the keyword argument list. For example: dict(one=1, two=2)

   dict(mapping) -> new dictionary initialized from a mapping object‘s  
  >>> dict3 = dict((‘F‘,70),(‘i‘,105),(‘s‘,115),(‘h‘,104),(‘C‘,67))
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: dict expect ed at most 1 arguments, got 5
  >>> dict3 = dict(((‘F‘,70),(‘i‘,105),(‘s‘,115),(‘h‘,104),(‘C‘,67)))
  >>> dict3
  {‘F‘: 70, ‘i‘: 105, ‘s‘: 115, ‘h‘: 104, ‘C‘: 67}

  (key, value) pairs

  >>> dict4 = dict(code = ‘編程改變世界‘, draw = ‘每一筆都是一個世界‘ )
  >>> dict4
  {‘code‘: ‘編程改變世界‘, ‘draw‘: ‘每一筆都是一個世界‘}
  >>> dict4 = dict(‘code‘ = ‘編程改變世界‘, draw = ‘每一筆都是一個世界‘ )
  File "<stdin>", line 1
  SyntaxError: keyword can‘t be an expression

 

有則更改,沒有則創建

  >>> dict4[‘code‘] = ‘學習編程就可以改變世界‘
  >>> dict4[‘student‘] = ‘天才第一步,卻是....‘
  >>> dict4
  {‘code‘: ‘學習編程就可以改變世界‘, ‘draw‘: ‘每一筆都是一個世界‘, ‘student‘: ‘天才第一步,卻是....‘}

dict() 工廠函數(類型) str(), int(),list(),tuple() ...

fromkeys(...) 會重新創建新的字典

  dict.fromkeys(s[,v]) -> New dict with keys from S and values equal to v (v defaults to None)

  >>> dict1 = {}

  >>> dict1.fromkeys((1,2,3))
  {1: None, 2: None, 3: None}
  >>> 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‘)}
  >>> dict1.fromkeys((1,3),‘數字‘)
  {1: ‘數字‘, 3: ‘數字‘}
  >>> dict1
  {}

keys(),values(),items()

  >>> dict1 = dict1.fromkeys(range(32),‘贊‘)
  >>> dict1
  {0: ‘贊‘, 1: ‘贊‘, 2: ‘贊‘, 3: ‘贊‘, 4: ‘贊‘, 5: ‘贊‘, 6: ‘贊‘, 7: ‘贊‘, 8: ‘贊‘, 9: ‘贊‘, 10: ‘贊‘, 11: ‘贊‘, 12: ‘贊‘, 13: ‘贊‘, 14: ‘贊‘, 15: ‘贊‘, 16: ‘贊‘, 17: ‘贊‘, 18: ‘贊‘, 19: ‘贊‘, 20: ‘贊‘, 21: ‘贊‘, 22: ‘贊‘, 23: ‘贊‘, 24: ‘贊‘, 25: ‘贊‘, 26: ‘贊‘, 27: ‘贊‘, 28: ‘贊‘, 29: ‘贊‘, 30: ‘贊‘, 31: ‘贊‘}

  >>> for eachkey in dict1.keys():
  ... print(eachkey)
  ...

  >>> for eachvalue in dict1.values():
  ... print(eachvalue)
  ...

 返回的是元組

  >>> for eachitem in dict1.items():
  ... print(eachitem)
  ...

  

  >>> print(dict1[31])
  贊

 訪問不存在的元素

  >>> print(dict1[32])
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  KeyError: 32

  >>> dict1.get(32)
  >>> print(dict1.get(32))\
  ...
  None
  >>> print(dict1.get(32))
  None
  >>> print(dict1.get(32,‘沒有‘))
  沒有

 判斷鍵在沒在字典中 成員操作符 in not in

  >>> 31 in dict1
  True
  >>> 33 in dict1
  False

 序列匹配的是值

 clear() 清空字典 存用戶信息時會有風險

  >>> dict1.clear()
  >>> dict1
  {}
  >>> dict1 = {}
  >>> a = {‘姓名‘: ‘俊傑‘}
  >>> b = a
  >>> b
  {‘姓名‘: ‘俊傑‘}
  >>> a = {}
  >>> a
  {}
  >>> b
  {‘姓名‘: ‘俊傑‘}

  >>> a = b
  >>> a
  {‘姓名‘: ‘俊傑‘}
  >>> b
  {‘姓名‘: ‘俊傑‘}
  >>> a.clear()
  >>> a
  {}
  >>> b
  {}

 copy()

 賦值只是貼了一個標簽,復制創建新的復制域

  >>> a = {1:‘one‘, 2:‘two‘,3:‘three‘}
  >>> b = a.copy()
  >>> c = a
  >>> c
  {1: ‘one‘, 2: ‘two‘, 3: ‘three‘}
  >>> a
  {1: ‘one‘, 2: ‘two‘, 3: ‘three‘}
  >>> b
  {1: ‘one‘, 2: ‘two‘, 3: ‘three‘}
  >>> id(a)
  139890364904936
  >>> id(b)
  139890303134744
  >>> id(c)
  139890364904936

 pop() popitem() 隨機彈

  >>> a.pop(2)
  ‘two‘
  >>> a.popitem()
  (3, ‘three‘)

 setdefalt(key[,value])

  >>> a
  {1: ‘one‘}
  >>> a.setdefault(‘小白‘)
  >>> a
  {1: ‘one‘, ‘小白‘: None}  
  >>> a.setdefault(5,‘five‘)
  ‘five‘
  >>> a
  {1: ‘one‘, ‘小白‘: None, 5: ‘five‘}

 a.update(b) 通過b的key對應的屬性去修改a,有則修改 沒有則添加

  >>> b = {‘小白‘: ‘狗‘}
  >>> a.update(b)
  >>> a
  {1: ‘one‘, ‘小白‘: ‘狗‘, 5: ‘five‘}

  >>> b = {‘小黃‘ : ‘da狗‘}
  >>> a.update(b)
  >>> a
  {1: ‘one‘, ‘小白‘: ‘狗‘, 5: ‘five‘, ‘小黃‘: ‘da狗‘}

python--15 字典:當索引不好用