如何在另一个dict中的Python dict中找到特定项?

时间:2017-02-08 14:44:43

标签: python

让我们说我有一个类似下面的Python词典:

sample_dict = {'Grade': {'Aya':4.0, 'John':3.0, 'Anna':1.0},
     'Address': {'Aya':'California', 'John':'Canada', 'Anna':'Mexico'},
     'School': 'Harvard University',
     'Nationality':{'Aya':'Japanese', 'John':'American', 'Anna':'American'}
    }

我很困惑如何操作代码,我只是传递参数来搜索,例如。 Aya ,结果如下:

Grade: Aya: 4.0
Address: Aya:California
School: Harvard University
Nationality: Aya: Japanese

更好的是:

Aya
Grade: 4.0
Address: California
School: Harvard University
Nationality: Japanese

这是我刚刚开始的事情:

def get_info(name):
    for key, value in sample_dict:
        print(name)
        if type(value) is dict:
            for people, equivalent in value:
                if(equivalent[name]):
                    print key, equivalent[name] 
                else:
                    print ("Not Found!")
        else:
            print key, value[key]
  
    

{'等级':{' John':3.0,' Aya':4.0,' Anna':1.0},&# 39;国籍':{' John':' American',' Aya':'日语' Anna' Anna&# 39;:' American'},' School':     '哈佛大学'地址':{' John':'加拿大' Aya':     '加利福尼亚'安娜':'墨西哥'}}

  
           

ValueError Traceback(最近一次调用   最后)in()        19打印键,值[键]        20   ---> 21 get_info(' Aya')

     get_info(name)中的

        8         9 def get_info(name):   ---> 10为key,sample_dict中的值:        11打印(名称)        12如果type(value)是dict:

     

ValueError:要解压缩的值太多

3 个答案:

答案 0 :(得分:3)

这里存在很多潜在的陷阱,但是如果没有关于数据假设的更多细节,你可以通过单行词典理解来满足这个特定情况:

{k:(v['Aya'] if 'Aya' in v else v) for k,v in sample_dict.items()}

答案 1 :(得分:2)

sample_dict = {'Grade': {'Aya':4.0, 'John':3.0, 'Anna':1.0},
     'Address': {'Aya':'California', 'John':'Canada', 'Anna':'Mexico'},
     'School': 'Harvard University',
     'Nationality':{'Aya':'Japanese', 'John':'American', 'Anna':'American'}
    }

def get_info(name):
    _info = {}
    for key, val in sample_dict.items():
        try:
            if isinstance(val, dict):
                val = val[name]
            _info[key] = val
        except KeyError:
            return None
    return _info

答案 2 :(得分:0)

它应该像使用这样的函数一样简单:

def get_info(name):
    print(name, '\n'
                'Grade:', sample_dict['Grade'][name], '\n'
                'Address:', sample_dict['Address'][name], '\n'
                'School:', sample_dict['School'], '\n'
                'Nationality:', sample_dict['Nationality'][name])

然后在函数中使用您的任何名称,就像您想要的那样:

get_info('Aya')

Aya
Grade: 4.0
Address: California
School: Harvard University
Nationality: Japanese