[英]Python 2.7.8: Printing a sub-dictionary value?
我正在使用ConfigParser,它返回如下配置数据字典:
{'general': {'UserKey': 'thisisatestkey'}}
如果我只想打印UserKey键的值(在本例中为thisisatestkey),则通常只print "Your key is: {0}".format(mydictvar.get('UserKey'))
。
如果我仅将原始字典打印为字符串,则会得到上面的结果。 如果我使用上面的print语句,则会得到None的结果,因为字典根目录中没有名为UserKey的键。 如果我.get('general')
我得到: {'UserKey': 'thisisatestkey'}
显然,我可以像这样做一个前循环:
keydic = cp.get_config_data()
for m, k in keydic.iteritems():
for s, v in k.iteritems():
userkey = v
然后打印正常的用户密钥。 但是我想知道如何才能避免必须先进行整个for循环,而只是直接在行内打印织补值? 谢谢!
您可以使用
mydictvar['general']['UserKey']
或者,如果钥匙可能丢失
mydictvar.get('general', {}).get('UserKey')
mydictvar['general']
返回一个字典对象; 那么你可以申请[...]
该值以检索下一个关键。
这也适用于字符串格式:
>>> mydictvar = {'general': {'UserKey': 'thisisatestkey'}}
>>> print "Your key is: {0[general][UserKey]}".format(mydictvar)
Your key is: thisisatestkey
完全没有循环:
>>> my_dict = {'general': {'UserKey': 'thisisatestkey'}}
>>> my_dict['general']['UserKey']
'thisisatestkey'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.