简体   繁体   中英

Not Able to Access to Specific Values of Array of Dictionary inside a List in Python

Can you pleaser take a look at this code and let me know why I am not able to access the value of set of dictionaries in a list?

cars = [
{
  "brand": "Ford",
  "model": "Mustang",
  "year": 2016
  },
  {
  "brand": "Toyota",
  "model": "Corrola",
  "year": 2010
  }
]
print(thisdict["brand"])

for car in cars:
    for brand in car.items():
        print(brand["brand"])

You have list of dictionaries , not 'set of dictionaries in a list'

So inside print function access dict by index and then by key. Also remove nested loop:

cars = [
    {
        "brand": "ford",
        "model": "mustang",
        "year": 2016,
    },
    {
        "brand": "toyota",
        "model": "corrola",
        "year": 2010,
    },
]

print(cars[0]["brand"])

for car in cars:
    print(car["brand"])

You don't need the second loop.

for car in cars:
  print(car['brand'])

Ford
Toyota

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM