如何将用户输入与python中json文件中的多个目录进行比较

2024-05-17 16:40:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json文件“contacts.json”,其中包含:

{
"Lisa": {
    "birthday": "09-02-1990"
},
"Marge": {
    "birthday": "05-01-2010"
},
"Bart": {
    "birthday": "23-09-1935"
},
"Homer": {
    "birthday": "22-11-1990"
}
}

现在我需要编写一个代码来提取用户输入的输入名称的生日。 我写了这段代码,但它不起作用


import json

name = input('Enter name of the person you want to see his/her birthday ')

with open('contacts.json') as file:
    data = json.load(file)

for i in data[i]:
    if name == data[i]:
        print(data[i]['Birthday'])

    else:
        print('Person not found')

file.close()

Tags: 文件代码用户name名称jsondatafile
2条回答

此代码可能对您有所帮助

arr = { "Lisa": { "birthday": "09-02-1990" }, "Marge": { "birthday": "05-01-2010" }, "Bart": { "birthday": "23-09-1935" }, "Homer": { "birthday": "22-11-1990" } }

name = "lisa"

bs = "Person not found"
for k, v in arr.items():
    if name.lower() in k.lower():
        bs = "{0}'s birthday: {1}".format(k, v.get('birthday'))
        break
print(bs)

注意:对于Python2.x,使用arr.iteritems()而不是arr.items()

这应该满足您的要求:

import json

name = input('Enter name of the person you want to see his/her birthday ')

with open('contacts.json') as file:
    data = json.load(file)

birthday = ''

for value in data:
    if name == value:
        birthday = data[value]['birthday']
        break
    else:
        birthday = 'Person not found'

print(birthday)

file.close()

相关问题 更多 >