>>> a_dict = {'server': 'localhost', 'database': 'mysql'}
>>> a_dict
{'database': 'mysql', 'server': 'localhost'}
>>> x = {} #空字典
>>> x
{}
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{}
>>> d = dict(name='xiao', age=17)
>>> d
{'age': 17, 'name': 'xiao'}
>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'age': None, 'name': None, 'sex': None}
>>> aDict = {'name':'xiao', 'sex':'male', 'age':17}
>>> aDict['name']
'xiao'
>>> aDict['tel'] #键不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
aDict['tel']
KeyError: 'tel'
>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'chengdu'))
chengdu
>>> aDict['score'] = aDict.get('score',[])
>>> aDict['score'].append(98)
>>> aDict['score'].append(97)
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'xiao', 'sex': 'male'}
>>> aDict={'name':'xiao', 'sex':'male', 'age':17}
>>> for item in aDict.items():
print(item)
('name', 'xiao')
('sex', 'male')
('age', 17)
>>> for key in aDict: #不加特殊说明,默认输出键
print(key)
age
name
sex
>>> for key, value in aDict.items(): #序列解包用法
print(key, value)
age 17
name xiao
sex male
>>> aDict.keys() #返回所有键
dict_keys(['name', 'sex', 'age'])
>>> aDict.values() #返回所有值
dict_values(['xiao', 'male', 17])
>>> aDict['age'] = 18 #修改元素值
>>> aDict
{'age': 18, 'name': 'xiao', 'sex': 'male'}
>>> aDict['address'] = 'sichuan' #增加新元素
>>> aDict
{'age': 18, 'address': 'sichuan', 'name': 'xiao', 'sex': 'male'}
>>> aDict
{'age': 17, 'score': [98, 97], 'name': 'xiao', 'sex': 'male'}
>>> aDict.items()
dict_items([('age', 17), ('score', [98, 97]), ('name', 'xiao'), ('sex', 'male')])
>>> aDict.update({'a':'a','b':'b'})
>>> aDict
{'a': 'a', 'score': [98, 97], 'name': 'xiao', 'age': 17, 'b': 'b', 'sex': 'male'}
>>> import string
>>> import random
>>> x = string.ascii_letters + string.digits + string.punctuation
>>> y = [random.choice(x) for i in range(1000)]
>>> z = ''.join(y)
>>> d = dict()
>>> for ch in z: #使用字典保存每个字符出现次数
d[ch] = d.get(ch, 0) + 1
>>> print(d)
>>> {i:str(i) for i in range(1, 5)}
{1: '1', 2: '2', 3: '3', 4: '4'}
>>> x = ['A', 'B', 'C', 'D']
>>> y = ['a', 'b', 'b', 'd']
>>> {i:j for i,j in zip(x,y)}
{'A': 'a', 'C': 'b', 'B': 'b', 'D': 'd'}
>>> s = {x:x.strip() for x in (' he ', 'she ', ' I')}
>>> s
{' he ': 'he', ' I': 'I', 'she ': 'she'}
https://www.cnblogs.com/xiaoyh/p/9980311.html
联系客服