Issue
I want to know how to search for a line that has a certain name. This is my .txt file with json:
{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}, {"name": "Larry", "website": "google.com", "from": "Michigan"}, {"name": "Tim", "website": "apple.com", "from": "Alabama"}]}
This is my code
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"])
That prints out Scott, but is there a way to search the json file for the line with the name Scott? Ive tried print(y["people"]["name": "Scott"]) but that didnt work. I want the output to be {"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}
Solution
You can use a list comprehension to filter the list. e.g.
>>> 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'}]
Answered By - a'r Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.