[英]In dictionary of python how to print value of a key if it have multiple values stored?
[英]How to print multiple key values when a specifc key value matches in a nested dictionary
我有一个嵌套字典,其中包含从 json 中提取的键值对字典。 例如一个名为“some_dict”的嵌套字典:
{1: {'address': 'some address', 'status': 'some status', 'name': 'some name'},
2: {'address': 'some other address', 'status': 'some other status', 'name': 'some other name'}}
我需要在这个嵌套字典中搜索键 'status' 的特定值,当它匹配时,返回该字典的所有值。 但是,我在实现中不断收到一个关键错误,我不知道为什么。
# Based on this answer: https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-dictionaries-and-lists
def has_key_value(data, target):
for key, value in data.items():
if isinstance(value, dict):
yield from has_key_value(value, target)
elif key == target:
return true
for x in range(1, len(some_dict)):
if has_key_value(x, 'some status'):
#print the dictionary
我已经走了这么远,但我终生无法弄清楚如何在嵌套的 some_dict 中返回字典的内容。 我已经尝试了几件事,终于来到了这种工作方式:
for x in range(1, len(some_dict)):
if has_key_value(x, 'some status'):
print(some_dict[x])
除了在打印前 3 个字典之后,它会抛出一个 'KeyError: 4' 错误。 我已经检查过 some_dict 中的所有字典在它们的模式中都是相同的,所以我无法弄清楚为什么会出现错误。 想法?
您似乎使这变得比必要的复杂得多。 您似乎没有多层嵌套,因此您不必递归。 并且您只关心与给定值匹配的status
键,而不是任何其他键。
for d in some_dict.values():
if d['status'] == 'some status':
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.