Alex Petev
Alex Petev

Reputation: 489

How to print out a value for a key of the first member of a list of dictionaries

I need to print out the value of "text" where ID = 0 in this list of dictionaries:

{ "ID":"0", "Text":"Once upon a time"},
{ "ID":"1", "Text":"The good end"},
{ "ID":"2", "Text":"The bad end" }

I can print out all of the values for the key "text" but not just an individual one with the following snippet:

with open ('story.json', 'r') as storyFile:
   story = json.load(storyFile)

for passage in story:
   print(passage["Text"])

Upvotes: 0

Views: 54

Answers (2)

Abhranil
Abhranil

Reputation: 1

Use a loop to separate each object then try to print the specific key value pair.

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

Just use an if and specify your condition:

for passage in story:
    if passage["ID"] == "0":
       print(passage["Text"])

Upvotes: 2

Related Questions