开发者

python: problem with dictionary get method default value

I'm having a new problem here .. CODE 1:

try:
   urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D.get(val['name'])))
except KeyError:
   print "expected parameter not provided - "+val["name"]+" is missing"
   exit(0)

CODE 2:

try:
   urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D[val['name']]))
except KeyError:
   print "expected parameter not provided - "+val["name"]+" is missing"
   exit(0)

see the diffrence in serverInfo_D[val['name']] & serverInfo_D.get开发者_StackOverflow(val['name']) code 2 fails but code 1 works

the data

serverInfo_D:{'user': 'usr', 'pass': 'pass'} 
data: {'par1': 9995, 'extraparam1': 22}
val: {'par1','user','pass','extraparam1'}

exception are raised for for data dict .. and all code in for loop which iterates over val


From the docs (dict.get):

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

That is why your first code works and second doesn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜