0

所以我正在编写一个代码,要求我能够根据输入搜索整个字典,这需要是一个函数。理想情况下,用户可以输入一个值,程序会打印出所有包含此输入的子词典。这是我的代码,它不太好用

animal=dict()
animal['1']={'ID': '21012', 'plot':4, 'year':'1993', 'species': 'DM', 'weight': 42, 'hindfoot': 36, 'tag':'1EA0F9'}
animal['2']={'ID':'22012', 'plot':4, 'year':'1995', 'species': 'DM', 'weight': 31, 'hindfoot': 37, 'tag':'0D373C'}
animal['3']={'ID': '23012', 'plot':17, 'year':'1996', 'species': 'DM', 'weight': 25, 'hindfoot': 37, 'tag':'64C6CC'}
animal['4']={'ID': '24012','plot':21, 'year':'1996', 'species': 'PP', 'weight': 26, 'hindfoot': 22, 'tag':'1F511A'}
animal['5']={'ID': '25012', 'plot':22, 'year':'1997', 'species': 'DM', 'weight': 53, 'hindfoot': 35, 'tag':'2624'}
animal['6']={'ID': '26012', 'plot':17, 'year':'1997', 'species': 'OT', 'weight': 14, 'hindfoot': 18, 'tag':'2863'}
animal['7']={'ID': '27012', 'plot':18, 'year':'1997', 'species': 'OT', 'weight': 23, 'hindfoot': 21, 'tag':'2913'}
animal['8']={'ID': '28012', 'plot':13, 'year':'1998', 'species': 'OT', 'weight': 36, 'hindfoot': 19, 'tag':'2997'}
animal['9']={'ID': '29012', 'plot':6, 'year':'1999', 'species': 'PM', 'weight': 20, 'hindfoot': 20, 'tag':'406'}
animal['10']={'ID': '30000', 'plot':14, 'year':'2000', 'species': 'DM', 'weight': 41, 'hindfoot': 34, 'tag':'156'}

result=dict()

def search_data():
    key = raw_input ('Please Input Search Criteria:')
    for k in animal.items ():
        if key in animal['v']: #if k is in sub dictionary
            print animal ['v'] #print sub dictionary
            return results;


search_data();

因此,如果您输入一个 ID 号,程序应该打印具有该 ID 号的子词典。

4

1 回答 1

0

dict.items返回键、值对,并且您希望将'ID'每个 subdict 与用户输入进行匹配,因此您应该检查 if subdict['ID'] == key

def search_data():
    key = raw_input ('Please Input Search Criteria:')
    for k, subdict in animal.items():
        if key == subdict['ID']: 
            return k, subdict    #return key and the sub-dictionary


print search_data();

演示:

Please Input Search Criteria:29012
('9', {'plot': 6, 'weight': 20, 'year': '1999', 'ID': '29012', 'tag': '406', 'hindfoot': 20, 'species': 'PM'})
于 2013-11-08T04:08:04.897 回答