Zhuojing Xie
Zhuojing Xie

Reputation: 21

How to use lambda to mutiple dictionary values?

so i met a question during learning python. lets say i have a dictionary a

a = {'Andy':[2,4,6,8],'Bryce':[1,2,3], 'Charile': [3,6], 'David':[10], 'Elaine' :[5,10]}

how can i use lambda to multiple 2 to every number in a and return a new dict?

i tried new_a= list(map(lambda x: x * 2, a.values())) however, it return a list like [[2, 4, 6, 8, 2, 4, 6, 8], [1, 2, 3, 1, 2, 3], [3, 6, 3, 6], [10, 10], [5, 10, 5, 10]]

the new dict I want is actully:

new_a =  {'Andy':[4,8,12,16],'Bryce',[2,4,6], 'Charile': [6,12], 'David':[20], 'Elaine' :[10,20]}

Upvotes: 2

Views: 4344

Answers (4)

Zhibekchach
Zhibekchach

Reputation: 41

def create_dict(l1, l2, l3):
    return {e[0]:max(e[1], e[2]) for e in zip(l1, l2, l3)}

Using Dictionary Comprehension: this is quite a short way )) you can choose which items you want as keys or value.

Upvotes: 0

Zhibekchach
Zhibekchach

Reputation: 41

# using lambda:
clients = ["A", "B", "C"]
spending_rate = [83724, 64728, 3822]
entry_year = [1999, 2010, 2019]
analyzes = dict(
    zip(
        clients,
        map(
            lambda x : x,
            zip(spending_rate, entry_year)
        )
    )
)
print(analyzes)

Upvotes: 0

Hugo G
Hugo G

Reputation: 16496

Keep it simple.

Changing existing dict:

for key, value in a.items():
  a[key] = [2 * item for item in value]

Creating a new dict with the updated values:

b = dict()
for key, value in a.items():
  b[key] = [2 * item for item in value]

Using Dictionary comprehension

b = {key: [2 * item for item in value] for key, value in a.items()}

No idea what you need Lambda for here. This is done much easier without.

Upvotes: 3

Vivek Pabani
Vivek Pabani

Reputation: 452

You could try:

a = {'Andy':[2,4,6,8],'Bryce':[1,2,3], 'Charile': [3,6], 'David':[10], 'Elaine' :[5,10]}

new_a = dict(list((key, list(map(lambda i:i*2, value))) for key, value in a.items()))

Output:

{'Andy': [4, 8, 12, 16], 'Bryce': [2, 4, 6], 'Charile': [6, 12], 'David': [20], 'Elaine': [10, 20]}

Upvotes: 1

Related Questions