3 回答
TA贡献1821条经验 获得超6个赞
你可以使用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']
TA贡献1776条经验 获得超12个赞
这会让你:
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'}
TA贡献2039条经验 获得超7个赞
您可以使用列表理解来获取水果价格列表:
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']
添加回答
举报