python嵌套字典查找元素_如何计算嵌套字典中的所有元素?

本文介绍了如何在Python中处理嵌套字典,包括计算字典及子字典中的元素数量。通过示例展示了如何访问和计数嵌套结构中的元素,强调了正确组织数据结构的重要性。
摘要由CSDN通过智能技术生成

对于您的特定问题,您可以使用:>>> 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值