LEDIK
LEDIK

Reputation: 63

How to print nested dictionarie element?

I have this piece of python code here.

cars = {
  "car1" : {
    "name" : "Toyota Prius",
    "color": "gray",
    "year" : "2009"
  },
  "car2" : {
    "name" : "Nissan GT-R",
    "color": "white",
    "year" : "2007"
  },
  "car3" : {
    "name" : "Ford Mustang GT",
    "color": "black",
    "year" : "2014"
  }
}

My question is: How can i put this nest, into a loop and then print out the car name, that has a 2009 production year. Thank you!

Upvotes: 0

Views: 44

Answers (2)

SRG
SRG

Reputation: 345

In this use case value is also a dictionary.so access values as dictionary

print([v['name'] for k,v in cars.items() if v['year']=="2009"])

output

['Toyota Prius']

Upvotes: 1

techytushar
techytushar

Reputation: 803

This should work:

for tag, value in cars.items():
    if value['year'] == '2009':
        print(value['name'])

Upvotes: 1

Related Questions