[英]Python - How do I return a dict key according to value in nested dict?
I have a dictionary of dictionaries in Python. 我有Python字典词典。
I would like a way to go through each dict of dict, check the value of the 'val' key in each dictionary then return the initial dictionary key where 'val' == 0. 我想要一种方法来检查字典的每个字典,检查每个字典中“ val”键的值,然后返回初始字典键,其中“ val” == 0。
dict = {
1: {'x': 'a', 'val': 1},
2: {'x': 'b', 'val': 1},
3: {'x': 'c', 'val': 0},
4: {'x': 'c', 'val': 0}
}
I tried the following but that just return 3 and 4. 我尝试了以下操作,但是只返回3和4。
for itemid, iteminfo in data.items():
for key in iteminfo:
if iteminfo[key] == 0:
print(str(itemid))
In the example above I would like 3 returned as it's the first instance where 'val' == 0. 在上面的示例中,我希望返回3,因为这是'val'== 0的第一个实例。
If you just want the first occurrence of 'val' being paired with 0 (without any specific order, since dicts in python aren't ordered), you could use a break with the conditional statement inside your loop: 如果只想将'val'的第一次出现与0配对(没有任何特定顺序,因为python中的字典没有排序),则可以在循环中使用带有条件语句的break:
mydict = {
1: {'x': 'a', 'val': 1},
2: {'x': 'b', 'val': 1},
3: {'x': 'c', 'val': 0},
4: {'x': 'c', 'val': 0}
}
for key, value in mydict.items():
if value['val'] == 0:
print(key)
break
If the order is important, you can go with an ordered dict 如果顺序很重要,则可以按顺序订购字典
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.