Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过调用嵌套字典中的键和值tru输入来获取键_Python_Dictionary - Fatal编程技术网

Python 通过调用嵌套字典中的键和值tru输入来获取键

Python 通过调用嵌套字典中的键和值tru输入来获取键,python,dictionary,Python,Dictionary,我有这个嵌套的dict,我想得到key(类A或B),如果我调用key(john和19)tru input中的key和value,我该怎么做?Plss帮助 people = { "class A" : {"camille": 19, "krinny": 19, "eunisce": 18}, "class B" : {"john" : 19, "r

我有这个嵌套的dict,我想得到key(类A或B),如果我调用key(john和19)tru input中的key和value,我该怎么做?Plss帮助

people = {   
    "class A" : {"camille": 19, "krinny": 19, "eunisce": 18},
    "class B" : {"john" : 19, "roi" : 19}
}

对于这种访问,它不是一种超高效的数据结构。您需要在字典中搜索以找到您要查找的值。下面的示例返回第一个找到的。如果名称可能出现在多个类中,则可以返回列表

people = {   
    "class A" : {"camille": 19, "krinny": 19, "eunisce": 18},
    "class B" : {"john" : 19, "roi" : 19}
}


def findClass(name, people):
    '''
    Returns the first class with the name 
    or None if not found
    '''
    return next((k for k, v in people.items() if name in v), None)

    
findClass("john", people)
#class B

findClass("krinny", people)
# 'class A'

findClass("joe", people)
# None
有几种方法

(1) 钥匙存取

people["class B"]["john"] #will give you 19
(2) 迭代项目

for key1, item1 in people.items():
    # key1 is class A or class B
    # item1 are dictionaries for class A and class B
    print(key1, item1)
    for key2, item2 in item1.items(): # then iterate on the item1
        print(key2, item2)
将打印如下:

    class A {'camille': 19, 'krinny': 19, 'eunisce': 18}
    camille 19
    krinny 19
    eunisce 18
    class B {'john': 19, 'roi': 19}
    john 19
    roi 19
class1={“class A”:{“teacher”:“simbahan”,“Room”:201,“Schedule”:“MWF”},“class B”:{“teacher”:“krinny”,“Room”:202,“Schedule”:“TTh”}我有一个新的dict,但是如果我输入像simbahan或krinny这样的教师(value)的名字,那么输出是class A或class B,我该怎么做呢
    class A {'camille': 19, 'krinny': 19, 'eunisce': 18}
    camille 19
    krinny 19
    eunisce 18
    class B {'john': 19, 'roi': 19}
    john 19
    roi 19