Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using map() with dictionary

I have a dictionary.

prices = {'n': 99, 'a': 99, 'c': 147}

using map () I need to receive new dictionary :

def formula(value):
    value = value -value * 0.05
    return value
new_prices = dict(map(formula, prices.values()))

but it doesn't work

TypeError: cannot convert dictionary update sequence element #0 to a sequence

solving my code using map():

new_prices = {'n': 94.05, 'a': 94.05, 'c': 139.65}
like image 629
Khasan Tufan Avatar asked Dec 01 '25 12:12

Khasan Tufan


2 Answers

you can do this using zip and map

new_prices = dict(zip(prices, map(formula, prices.values())))
like image 186
Usman Arshad Avatar answered Dec 03 '25 01:12

Usman Arshad


Use dictionary comprehension:

new_prices = {k: formula(prices[k]) for k in prices}
print(new_prices)
# {'n': 94.05, 'a': 94.05, 'c': 139.65}
like image 41
Timur Shtatland Avatar answered Dec 03 '25 02:12

Timur Shtatland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!