gpt4 book ai didi

python - 如何用关键字搜索json文件中的某一行?

转载 作者:行者123 更新时间:2023-12-04 00:56:37 28 4
gpt4 key购买 nike

我想知道如何搜索具有特定名称的行。这是我的带有 json 的 .txt 文件:

{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}

这是我的代码

import json

file = open('data.txt', "r")
read = file.read()
y = json.loads(read)

first = y["people"][0]
second = y["people"][1]
third = y["people"][2]

print(y["people"][0]["name"])

这会打印出 Scott,但是有没有办法在 json 文件中搜索名为 Scott 的行?我试过 print(y["people"]["name": "Scott"]) 但这没有用。我希望输出为 {"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}

最佳答案

您可以使用 list comprehension过滤列表。例如

>>> people = y['people']
>>> people_named_scott = [p for p in people if p['name'] == 'Scott']
>>> people_named_scott
[{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]

关于python - 如何用关键字搜索json文件中的某一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62037666/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com