包含子键和子值的JSON文件

2024-09-29 21:47:18 发布

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

我有一个json文件,如下所示:

{"people": [{"name": "carlota", "birthday": "11/12/1945"}, 
            {"name": "mariana", "birthday": "25/08/1930"}, 
            {"name": "agustina", "birthday": "17/11/1943"}]}

如何在不必创建新词典的情况下获取“people”中的信息?因为这是我唯一能做的。这是我的密码:

import json

with open("cumple.txt", "r") as f: #cumple.txt is the file where my JSON is
    info = json.load(f)
l=[]
s=[]
print('we know the birthday of:')
for i in info['people']:
    print(i['name'])
    print(i['birthday'])
    l.append(i['name'])
    s.append(i['birthday'])

c=input("who's birthday want to know ? ")

dictionary = dict(zip(l, s))

if c in l:
    print('{} cumple el'.format(c), dictionary[c] )

else:
    print('we don\'t know the birthday of {}'.format(c)

Tags: ofthenameininfotxtjsonis
1条回答
网友
1楼 · 发布于 2024-09-29 21:47:18

字典通常是最好的方法。没有字典,你必须循环

for i in info:
    if i['name'] == c:
        print('{} cumple el {}'.format(c, i['birthday']))
        break
else:
    print('we don\'t know the birthday of {}'.format(c)

for循环正常结束而不是从break结束时,执行else:循环的else:

相关问题 更多 >

    热门问题