新增鍵值對
先定義一個空字典
>>> dic={}
直接將字典中不存在的key賦值來加
>>> dic['name']='zhangsan' >>> dic {'name': 'zhangsan'}
如果key或value都是變數也可以用這種方法
>>> key='age' >>> value=30 >>> dic[key]=value >>> dic {'age': 30, 'name': 'zhangsan'}
這裡可以看到字典中的資料並不是按先後順序排列的,如果有興趣,可以搜尋資料結構中的一個-雜湊表
也可以用字典的setdefault方法
>>> dic.setdefault('sex','male') 'male' >>> key='id' >>> value='001' >>> dic.setdefault(key,value) '001' >>> dic {'id': '001', 'age': 30, 'name': 'zhangsan', 'sex': 'male'}
#這裡有兩種方法
#方法1:###先取得key,然後透過dic[key ]取得value############>>> for key in dic: ... print 'key is %s,value is %s'%(key,dic[key]) ... key is id,value is 001 key is age,value is 30 key is name,value is zhangsan key is sex,value is male
>>> for key,value in dic.items(): ... print 'key is %s,value is %s'%(key,value) ... key is id,value is 001 key is age,value is 30 key is name,value is zhangsan key is sex,value is male