1. 程式人生 > >python-字典用法(50)

python-字典用法(50)

>>> adict = dict()
>>> dict(['ab','cd'])
{'a': 'b', 'c': 'd'}
>>> adict
{}
>>> bdict = dict([('name','bob'),('age','25')])
>>> bdict
{'name': 'bob', 'age': '25'}
>>> {}.fromkeys(['zhangsan','lisi','wangwu'],11)    #多個key對應一個值
{'zhangsan': 11, 'lisi': 11, 'wangwu': 11}
>>> for key in bdict:   #迴圈列印key和value
...     print('%s:%s' % (key,bdict[key]))
...
name:bob
age:25
>>> print('%(name)s:%(age)s' % bdict)
bob:25
>>> bdict['name'] = 'tom'   #字典有相同的key,則修改這個key對應的value
>>> bdict['email'] = '
[email protected]
' #沒有對應的key,新加對應的鍵值對 >>> bdict {'name': 'tom', 'age': '25', 'email': '[email protected]'} >>> del bdict['email'] #刪除對應的key和value >>> bdict {'name': 'tom', 'age': '25'} >>> bdict.pop('age') #彈出對應的key和value '25' >>> bdict {'name': 'tom'} >>> bdict.clear() #清空字典 >>> bdict {} >>> adict = dict([('name','bob'),('age',25)]) #定義字典 >>> adict {'name': 'bob', 'age': 25} >>> len(adict) #檢視字典長度 2 >>> hash(10) 10 >>> adict.keys() #檢視字典裡的所有key dict_keys(['name', 'age']) >>> adict.values() #檢視字典裡的所有value dict_values(['bob', 25]) >>> adict.items() dict_items([('name', 'bob'), ('age', 25)]) >>> adict.get('name') 'bob' >>> print(adict.get('qq')) #沒有這個key,返回None None >>> print(adict.get('qq','not found')) #沒有這個key,返回指定值 not found >>> print(adict.get('age','not found')) #有這個key,返回key對應的值 25 >>> adict.update({'phone':'13449065521'}) >>> adict {'name': 'bob', 'age': 25, 'phone': '13449065521'}