Home > Net >  using map() with dictionary
using map() with dictionary

Time:11-30

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}

CodePudding user response:

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}

CodePudding user response:

you can do this using zip and map

new_prices = dict(zip(prices, map(formula, prices.values())))

CodePudding user response:

Use map() with a helper lambda to create new dict

new_prices = dict(map(lambda item: (item[0], formula(item[1])), prices.items()))

output:

{'n': 94.05, 'a': 94.05, 'c': 139.65}

CodePudding user response:

First option (using a dict comprehension):

    prices = {'n': 99, 'a': 99, 'c': 147}
    
    
    def formula(value):
        value = value -value * 0.05
        return value

    #Using a dict comprehension and .items() [giving you key value tuples] instead of map()
    new_prices = {k: formula(v) for k, v in prices.items()}
    
    print(new_prices)
    # {'n': 94.05, 'a': 94.05, 'c': 139.65}

Second option (using map and defining the formula slightly differently [tuple as input]):

    #Define the formula with a key value pair (tuple) as input and return value
    def f_items(items):
        value = items[1] - items[1] * 0.05
        return items[0], value
    
    
    new_prices = dict(map(f_items, prices.items()))
    
    print(new_prices)
    # {'n': 94.05, 'a': 94.05, 'c': 139.65}

CodePudding user response:

You could do that using lambda with map:

new_prices = dict(map(lambda v: (v[0], formula(v[1])), prices.items()))

Output:

{'n': 94.05, 'a': 94.05, 'c': 139.65}

CodePudding user response:

When you create a map, you get a map object. It's nice to have an helper function to iterate through this object.

def print_results(map_object):
    for i in map_object:
        print(i)

def formula(value):
    return value * 0.95 # one-liner

m = map(formula, prices.values())

print_results(m)

# output
94.05
94.05
139.65
  • Related