Not a bot
Not a bot

Reputation: 1

Some help for a beginner

I have to make a list out of some elements in a dictionary in Python 3:

fruits = {
    'apple' : {'price' : '13', weight : '15'},
    'orange' : {'price' : '8', weight : '11'}
}

How can I make a list that only shows me the price of all fruits?

Upvotes: 0

Views: 86

Answers (3)

Sajal Shrestha
Sajal Shrestha

Reputation: 118

You can use list comprehension to get the list of fruit prices:

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)

This gives you a list of fruit prices:

['13', '8']

Upvotes: 0

Tibebes. M
Tibebes. M

Reputation: 7548

you may use operator.itemgetter as the following

from operator import itemgetter

fruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8', 'weight' : '11'}}

priceList = list(map(itemgetter('price'), fruits.values()))

print(priceList)

output:

['13', '8']

Upvotes: 2

Arvind Kumar
Arvind Kumar

Reputation: 451

This will get you that:

fruits = {'apple' : {'price' : '13', 'weight' : '15'}, 'orange' : {'price' : '8', 
         'weight' : '11'}}
output = {k:v['price'] for k,v in fruits.items()}
print(output)

which results in:

{'apple': '13', 'orange': '8'}

Upvotes: 0

Related Questions