[英]Accessing nested dictionary items in Python
I am trying to format a string using an item from a nested dictionary (below) 我试图使用嵌套字典中的项目格式化字符串(下面)
people = {
'Alice': {
'phone': '2341',
'addr': '87 Eastlake Court'
},
'Beth': {
'phone': '9102',
'addr': '563 Hartford Drive'
},
'Randy': {
'phone': '4563',
'addr': '93 SW 43rd'
}
}
From the above (simple) dictionary, I want to format a string to print out Randy's phone extension. 从上面的(简单)字典中,我想格式化一个字符串以打印出Randy的电话分机。
I am able to access all of his details using: 我可以使用以下方式访问他的所有详细信息:
print("Randy's phone # is %(Randy)s" % people)
But I'm not sure on how to go deeper into the dictionary to single out just the phone number from the dictionary. 但我不知道如何更深入地进入字典,只从字典中挑出电话号码。
I am using Python 3.3, by the way. 顺便说一下,我正在使用Python 3.3。
Use the new string formatting : 使用新的字符串格式 :
print("Randy's phone # is {0[Randy][phone]}".format(people))
or 要么
print("Randy's phone # is {Randy[phone]}".format(**people))
There's no point in passing the entire dictionary if you only use one value. 如果你只使用一个值,那么传递整个字典是没有意义的。
print("Randy's phone # is {}".format(people['Randy']['phone']))
or 要么
print("Randy's phone # is %s" % people['Randy']['phone'])
will also work. 也会工作。
Passing the dict makes sense if you have a lot of these format strings and do not know which values they use, and want them to be able to access any value. 如果你有很多这些格式字符串并且不知道它们使用哪些值,并希望它们能够访问任何值,那么传递dict是有意义的。
Or if you use many values in the format string and passing them individually is just too verbose. 或者,如果在格式字符串中使用多个值并单独传递它们就太冗长了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.