在嵌套的 Python 字典中搜索键

编程入门 行业动态 更新时间:2024-10-24 04:40:08
本文介绍了在嵌套的 Python 字典中搜索键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些这样的 Python 词典:

I have some Python dictionaries like this:

A = {id: {idnumber: condition},....

例如

A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....

我需要搜索字典是否有任何 idnumber == 11 并用 condition 计算一些东西.但是如果在整个字典中没有任何idnumber == 11,我需要继续next字典.

I need to search if the dictionary has any idnumber == 11 and calculate something with the condition. But if in the entire dictionary doesn't have any idnumber == 11, I need to continue with the next dictionary.

这是我的尝试:

for id, idnumber in A.iteritems(): if 11 in idnumber.keys(): calculate = ...... else: break

推荐答案

离你很近了.

idnum = 11 # The loop and 'if' are good # You just had the 'break' in the wrong place for id, idnumber in A.iteritems(): if idnum in idnumber.keys(): # you can skip '.keys()', it's the default calculate = some_function_of(idnumber[idnum]) break # if we find it we're done looking - leave the loop # otherwise we continue to the next dictionary else: # this is the for loop's 'else' clause # if we don't find it at all, we end up here # because we never broke out of the loop calculate = your_default_value # or whatever you want to do if you don't find it

如果您需要知道内部 dict 中有多少个 11 作为键,您可以:

If you need to know how many 11s there are as keys in the inner dicts, you can:

idnum = 11 print sum(idnum in idnumber for idnumber in A.itervalues())

这是有效的,因为一个键只能在每个 dict 中出现一次,所以您只需要测试该键是否存在.in 返回等于 1 和 0 的 True 或 False,所以sum是idnum出现的次数.

This works because a key can only be in each dict once so you just have to test if the key exits. in returns True or False which are equal to 1 and 0, so the sum is the number of occurences of idnum.

更多推荐

在嵌套的 Python 字典中搜索键

本文发布于:2023-11-12 03:44:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580416.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字典   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!