字典创建、删除
aDict = {
'server':'db.diveintopython3.org','database':'mysql'}
aDict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
x = dict()
keys = ['a','b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = dict(zip(keys,values))
dictionary
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
d = dict(name='Dong', age=39)
d
{'age': 39, 'name': 'Dong'}
aDict = dict.fromkeys(['name','age','sex'])
aDict
{'age': None, 'name': None, 'sex': None}
{i:str(i) for i in range(1,5)}
{1: '1', 2: '2', 3: '3', 4: '4'}
字典元素的访问
aDict = {
'age':39,'score':[98, 97],'name': 'Dong','sex':'male'}
def fun(x):
if x in aDict:
print(aDict[x])
else:
print('Not Exists.')
fun('Age')
Not Exists.