将 map() 与字典一起使用

Kha*_*fan 2 python dictionary list

我有一本字典。

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

Run Code Online (Sandbox Code Playgroud)

使用map()我需要接收新的字典:

def formula(value):
    value = value -value * 0.05
    return value
Run Code Online (Sandbox Code Playgroud)
new_prices = dict(map(formula, prices.values()))
Run Code Online (Sandbox Code Playgroud)

但它不起作用

TypeError: cannot convert dictionary update sequence element #0 to a sequence
Run Code Online (Sandbox Code Playgroud)

使用以下方法解决我的代码map()

new_prices = {'n': 94.05, 'a': 94.05, 'c': 139.65}
Run Code Online (Sandbox Code Playgroud)

Usm*_*had 7

你可以使用zip和来做到这一点map

new_prices = dict(zip(prices, map(formula, prices.values())))
Run Code Online (Sandbox Code Playgroud)

  • 无需调用“prices.keys()”;`zip` 在内部对每个参数调用 `iter`,并且 `iter(prices)` 根据需要生成键。 (2认同)