字典添加键值对的两种方法(setdefault):
dic={} #定义一个空字典
dic['name']='zhangsan'#添加键值对1
#添加键值对2,key,value都是变量
>>> key='age'
>>> value=30
>>> dic[key]=value
>>> dic
{'age': 30, 'name': 'zhangsan'}
#添加键值对3
dic.setdefault('sex','male')
#4
key='id'
value='001'
dic.setdefault(key,value)
print 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 male1234567
#方法2:对字典items()方法返回的元组列表进行序列解包
>>> 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