2024-05-15 00:26:56 发布
网友
我有以下意见:
{ 'foo': { 'name': 'bar', 'options': None, 'type': 'qux' }, 'baz': { 'name': 'grault', 'options': None, 'type': 'plugh' }, }
顶级键的名称在运行时未知。我无法确定如何获取顶级键的名称,其中type的值为plugh。我尝试过各种迭代器、循环、理解等,但我对Python不是很在行。任何指点都将不胜感激
type
plugh
尝试迭代dict键并检查元素
for key in d: if(d[key]['type'] == 'plugh'): print(key)
baz
您需要像这样迭代数据:
def top_level_key(search_key, data): for key, value in data.items(): if value['type'] == search_key: return key print(top_level_key('plugh', data_dict))
试试这个:
for key, inner_dict in dict_.items(): if inner_dict['type'] == 'plugh': print(key)
或者,如果使用一行程序来获取与条件匹配的第一个密钥:
key = next(key for key, inner_dict in dict_.items() if inner_dict['type'] == 'plugh') print(key)
输出:
尝试迭代dict键并检查元素
您需要像这样迭代数据:
试试这个:
或者,如果使用一行程序来获取与条件匹配的第一个密钥:
输出:
相关问题 更多 >
编程相关推荐