[英]Python 2.7.8: Printing a sub-dictionary value?
I'm using ConfigParser which returns a dictionary of configuration data as such: 我正在使用ConfigParser,它返回如下配置数据字典:
{'general': {'UserKey': 'thisisatestkey'}}
If I want to simply print the value of the UserKey key (in this case thisisatestkey), then I generally just do a print "Your key is: {0}".format(mydictvar.get('UserKey'))
. 如果我只想打印UserKey键的值(在本例中为thisisatestkey),则通常只
print "Your key is: {0}".format(mydictvar.get('UserKey'))
。
If I just print out the raw dict to a string I get the above. 如果我仅将原始字典打印为字符串,则会得到上面的结果。 If I use the print statement above I get result of None since there is no key in the root of the dict called UserKey.
如果我使用上面的print语句,则会得到None的结果,因为字典根目录中没有名为UserKey的键。 If I
.get('general')
I just get: {'UserKey': 'thisisatestkey'}
如果我
.get('general')
我得到: {'UserKey': 'thisisatestkey'}
Obviously I could do a fore loop like so: 显然,我可以像这样做一个前循环:
keydic = cp.get_config_data()
for m, k in keydic.iteritems():
for s, v in k.iteritems():
userkey = v
and then print userkey which works fine. 然后打印正常的用户密钥。 But I want to know how I can just avoid having to do the entire for loop first and just print the darned value right inline?
但是我想知道如何才能避免必须先进行整个for循环,而只是直接在行内打印织补值? Thanks!
谢谢!
You can use 您可以使用
mydictvar['general']['UserKey']
Or, if keys might be missing 或者,如果钥匙可能丢失
mydictvar.get('general', {}).get('UserKey')
mydictvar['general']
returns a dictionary object; mydictvar['general']
返回一个字典对象; you can then just apply [...]
to that value to retrieve the next key. 那么你可以申请
[...]
该值以检索下一个关键。
This works in string formatting too: 这也适用于字符串格式:
>>> mydictvar = {'general': {'UserKey': 'thisisatestkey'}}
>>> print "Your key is: {0[general][UserKey]}".format(mydictvar)
Your key is: thisisatestkey
simply without loop: 完全没有循环:
>>> my_dict = {'general': {'UserKey': 'thisisatestkey'}}
>>> my_dict['general']['UserKey']
'thisisatestkey'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.