按记录搜索字典



我无法在字典中找到超过一条记录的人。

例如:如果输入年龄、性别、城市,则显示年龄+性别+城市;如果输入性别、城市,则显示性别+城市。

people={'1': {'name': 'John', 'surname': 'Mclachan', 'age': '27', 'city': 'London', 'sex': 'Male', 'married': 'Yes', 'phoneNo': '00001'}, '2': {'name': 'Marie', 'surname': 'Rose', 'age': '22', 'city': 'London', 'sex': 'Female', 'married': 'No', 'phoneNo': '00002'}, '3': {'name': 'Luna', 'surname': 'Stallone', 'age': '24', 'city': 'Edinburgh', 'sex': 'Female', 'married': 'No', 'phoneNo': '00003'}, '4': {'name': 'Peter', 'surname': 'Griffin', 'age': '29', 'city': 'Edinburgh', 'sex': 'Male', 'married': 'Yes', 'phoneNo': '00004'}}
def find_people():

city = input('Input city >> ').title()
surname = input('surname >> ').title()
name_p = input('name >> ').title()
sex = input('sex >> ').title()
age = input('age >> ').title()
if any(record["name"] == name_p or record['city'] == city or record['sex'] == sex or record['age'] == age or record['surname']== surname for record in people.values()):
for x in people:
if people[x]['name'] == name_p and people[x]['city'] == city or people[x]['name'] == name_p or people[x]['city'] == city or people[x]['sex'] == sex
or people[x]['city'] == city and people[x]['sex'] == sex and people[x]['age'] == age:
#if people[x]['name'] == name_p and people[x]['city'] == city:
print('n Person_ID:', x)
print('-------------')
for key, value in people[x].items():
print(key+':', value)

你的描述是相当混乱的,所以我试着把代码的最小变化只是找到一个matching记录,你可以尝试使用以下简化的代码和修改自己所需的display格式:

基本工作是通过surname+ first_name+ city搜索任何匹配并显示记录。

def find_people():

city = input('Input city >> ').title()
surname = input('surname >> ').title()
first_name = input('name >> ').title()
sex = input('sex >> ').title()
age = input('age >> ')         # don't need .title()
records = people.values()
#print(records)
# search for a good matching record - by Surname+ Name + city
for record in records:
if (record['name'] == first_name and record['surname'] == surname and record['city'] == city):
print(record)
"""
#if people[x]['name'] == name_p and people[x]['city'] == city:
#
print('n Person_ID:', p)
print('-------------')
for key, value in people[p].items():
print(key +':', value)
"""
if __name__ == '__main__':
find_people()
print('Done')

输出:

Input city >> Edinburgh
surname >> Stallone
name >> Luna
sex >> Male
age >> 24
{'name': 'Luna', 'surname': 'Stallone', 'age': '24', 'city': 'Edinburgh', 'sex': 'Female', 'married': 'No', 'phoneNo': '00003'}
Done    

相关内容

  • 没有找到相关文章

最新更新