Home > OS >  Looking up a key and value nested in a dictionary and list
Looking up a key and value nested in a dictionary and list

Time:06-15

I have the following data and am struggling to look up the months where a colour or name is specified e.g. the month where the colour is yellow:

data = {'gems': [{'name': 'garnet', 'colour': 'red', 'month': 'January'},
                 {'name': 'amethyst', 'colour': 'purple', 'month': 'February'},
                 {'name': 'bloodstone', 'colour': 'green/red', 'month': 'March'},
                 {'name': 'diamond', 'colour': 'clear', 'month': 'April'},
                 {'name': 'emerald', 'colour': 'green', 'month': 'May'},
                 {'name': "cat's eye", 'colour': 'yellow', 'month': 'June'},
                 {'name': 'turquoise', 'colour': 'turquoise', 'month': 'July'},
                 {'name': 'sardonyx', 'colour': 'red', 'month': 'August'},
                 {'name': 'peridot', 'colour': 'green', 'month': 'September'},
                 {'name': 'opal', 'colour': 'iridescent', 'month': 'October'},
                 {'name': 'topaz', 'colour': 'yellow', 'month': 'November'},
                 {'name': 'ruby', 'colour': 'red', 'month': 'December'}]}

I tried to achieve this by doing the following where I tried to create a list that would give the location where colour = yellow and then was going to use it look up the months but receive an attribute error:

nest = data['gems']
location = []
for x in range(len(nest)):
    for k, v in nest.items():
        nest.items() == ("colour", "yellow")
    location[x] = [x]

return location

CodePudding user response:

You can do it like this

location = []
for gem in data['gems']:
    if gem['colour'] == 'yellow':
        location.append(gem['month'])
print(location) # ['June', 'November']

Or with list comprehensions

location = [gem['month'] for gem in data['gems'] if gem['colour'] == 'yellow']

CodePudding user response:

You can do:

yellow_items = list(filter(lambda x:x['colour'] =='yellow', data['gems']))
yellow_months = [x['month'] for x in yellow_items]

output:

['June', 'November']

Or if you can use pandas:

import pandas as pd
df = pd.DataFrame(data['gems'])
yellow_months = df.loc[df['colour']=='yellow']['month'].tolist()

output:

['June', 'November']

CodePudding user response:

do this:

for record in data['gems']:
    record = record
    output = record['month']   ':'  record['colour']
    print(output)
  • Related