对于您的特定问题,您可以使用:>>> d={'fruit':
{'orange': 'orange', 'apple': 'red', 'banana': 'yellow'},
'vegetables':
{'lettuce': 'green', 'beet': 'red', 'pumpkin': 'orange'}}
>>> len(d)
2 # that is 1 reference for 'fruit' and 1 for 'vegetables'
>>> len(d['fruit'])
3 # 3 fruits listed...
>>> len(d['vegetables'])
3 # you thought of three of those...
>>> len(d['fruit'])+len(d['vegetables'])
6
虽然您可以使用各种工具,Python必须计算这个简单字典中的元素,但更有趣和更有成效的事情是首先考虑数据的结构。
Python的基本数据结构是lists, sets, tuples, and dictionaries。这些数据结构中的任何一个都可以通过引用“保存”自身或其他数据结构的任何嵌套版本。>>> l = [1, [2, 3, [4]], [5, 6]]
>>> len(l)
3
>>> l[0]
1
>>> l[1]
[2, 3, [4]]
>>> l[2]
[5, 6]
第一个元素是整数1。元素1和2是列表本身。其他任何基本的Python数据结构也是如此。这些是recursive data structures。你可以用pprint打印它们
如果更好地组织字典,则使用Python最简单的工具更容易从字典中提取信息:>>> color='color'
>>> family='family'
>>> sensation='sensation'
>>> good_things={
'fruit':
{
'orange':
{
color: 'orange',
family: 'citrus',
sensation: 'juicy'
},
'apple':
{
color: ['red','green','yellow'],
family:'Rosaceae',
'sensation': 'woody'
},
'banana':
{
color: ['yellow', 'green'],
family: 'musa',
sensation: 'sweet'
}
},
'vegatables':
{
'beets':
{
color: ['red', 'yellow'],
family: 'Chenopodiaceae',
sensation: 'sweet'
},
'broccoli':
{
color: 'green',
family: 'kale',
sensation: 'The butter you put on it',
}
}
}
现在,对该数据的查询更有意义:>>> len(good_things)
2 # 2 groups: fruits and vegetables
>>> len(good_things['fruit'])
3 # three fruits cataloged
>>> len(good_things['vegetables'])
2 # I can only think of two vegetables...
>>> print good_things['fruit']['apple']
{'color': ['red', 'green', 'yellow'], 'sensation': 'woody', 'family': 'Rosaceae'}
>>> len(good_things['fruit']['apple']['color'])
3 # apples have 3 colors