[英]printing specific values from a list in a dictionary
我正在嘗試在字典中打印特定值。
my_dictionary = {'url': 'www.google.com', 'value': [{'car': 'Mercedes', 'engine': 'Gas'}, {'car': 'Audi', 'engine': 'Diesel'}, {'car': 'Volkswagen', 'engine': 'Hybrid'}]
預期結果: Gas, Diesel, Hybrid
for x in my_dictionary:
y= my_dictionary['value'][0]['engine']
print(y)
以上是我的代碼,但它給了我回報: Gas Gas
my_dictionary
有兩個鍵,因此x
將依次為'url'
和'value'
。 然后你實際上並沒有在 print 語句中使用你的迭代變量,只是兩次從第一個value
元素打印。
您實際上需要遍歷'value'
列表中的條目。 你想要的看起來像這樣:
for entry in my_dictionary['value']:
print(entry['engine'])
要添加到以前的答案,這可能是列表理解的一個很好的候選者:
print([entry["engine"] for entry in my_dictionary["value"]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.