I'm trying to print specific values inside a dictionary.
my_dictionary = {'url': 'www.google.com', 'value': [{'car': 'Mercedes', 'engine': 'Gas'}, {'car': 'Audi', 'engine': 'Diesel'}, {'car': 'Volkswagen', 'engine': 'Hybrid'}]
Expected outcome: Gas, Diesel, Hybrid
for x in my_dictionary:
y= my_dictionary['value'][0]['engine']
print(y)
Above is my code but it gives me back: Gas Gas
my_dictionary
has two keys, so x
will successively be 'url'
and 'value'
. And then you're not actually using your iteration variable in the print statement, just printing from the first element of value
both times.
You need to actually iterate over the entries in the 'value'
list. What you intend looks like this:
for entry in my_dictionary['value']:
print(entry['engine'])
To add to the previous answer, this may be a good candidate for list comprehension:
print([entry["engine"] for entry in my_dictionary["value"]])
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.