我必须从Python 3的字典中列出一些元素。
fruits = {
'apple' : {'price' : '13', weight : '15'},
'orange' : {'price' : '8', weight : '11'}
}
我该如何列出仅显示所有水果价格的清单?
答案 0 :(得分:2)
您可以使用operator.itemgetter
如下
from operator import itemgetter
fruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8', 'weight' : '11'}}
priceList = list(map(itemgetter('price'), fruits.values()))
print(priceList)
输出:
['13', '8']
答案 1 :(得分:0)
这将为您带来:
fruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8',
'weight' : '11'}}
output = {k:v['price'] for k,v in fruits.items()}
print(output)
结果为:
{'apple': '13', 'orange': '8'}
答案 2 :(得分:0)
您可以使用列表推导获取水果价格列表:
fruits = {
"apple": {"price": "13", "weight": "15"},
"orange": {"price": "8", "weight": "11"},
}
# using list comprehension
fruits_prices = [fruit_info.get("price") for fruit_info in fruits.values()]
# using loop
fruit_prices = []
for fruit_info in fruits.values():
fruit_prices.append(fruit_info.get("price"))
print(fruit_prices)
这会给您列出水果价格:
['13', '8']