Home > Blockchain >  How to extract information in a dictionary in json
How to extract information in a dictionary in json

Time:11-14

data = 

{'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'},
  {'name': 'emerald', 'colour': 'green', 'month': 'May'},
  {'name': "cat's eye", 'colour': 'yellow', 'month': 'June'},
  {'name': 'sardonyx', 'colour': 'red', 'month': 'August'},
  {'name': 'peridot', 'colour': 'green', 'month': 'September'},
  {'name': 'ruby', 'colour': 'red', 'month': 'December'}]}

How do I create a list of colours and then just find the months with the colour red?

I've tried for and if, but I keep getting the error message

string indices must be integers

CodePudding user response:

Because you have dictionaries within a list, you can use a list-comprehension with nested if logic to filter out those values you don't want:

[x['month'] for x in data['gems'] if x['colour'] == 'red']

Returns:

['January', 'August', 'December']
  • Related