【问题标题】:Creating A Search Function From Dictionaries In Python在 Python 中从字典创建搜索函数
【发布时间】:2013-11-08 03:59:38
【问题描述】:

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

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 号的子词典。

【问题讨论】:

  • 它给你什么错误?
  • 您实际上是否有多个具有相同 ID 号的子词典?否则,只需使用 ID 作为密钥。在任何情况下,使用整数作为 dict 中的键都是笨拙且毫无意义的,如果您这样做,请使用 list 来保存您的所有 dicts。

标签: python function search dictionary


【解决方案1】:

dict.items 返回键、值对,并且您希望将每个 subdict 的 'ID' 与用户输入匹配,因此您应该检查是否为 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'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多