0

I have two lists

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heroes = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

From these lists, I want a dict of {'name': 'hero'} for each name,hero using a lambda function. Here's my desired output:

{'Bruce': 'Batman', 'Clark': 'Superman', 'Peter': 'Spiderman', 'Logan': 'Wolverine', 'Wade': 'Deadpool'}

I have the code below that works but when I try to put it together using a lambda function I don't get as expected. Here is the code that works using dictionary comprehensions

dc_dict = {name: hero for name, hero in zip(names, heroes)}
print(dc_dict)

I am trying to replicate the above logic using lambda function and that doesn't work as expected. Here is what I have come up with.

l_dict = dict(lambda names[name]:heroes[hero] for (name, hero) in zip(names, heroes))
print(l_dict)

TIA

arnaud
  • 3,293
  • 1
  • 10
  • 27
vow7779
  • 5
  • 4
  • 5
    You could use : `dict(zip(names, heroes))` that'll be easier. Why use a `lambda`? – arnaud Jun 12 '20 at 15:01
  • 1
    You just don't need a lambda here, but it should generate a tuple with two items because dict expects an iterable of such tuples. The code in parentheses in the last example is a generator expression (similar to dict comprehension) which doesn't need lambda ib this case. – Michael Butscher Jun 12 '20 at 15:01
  • 1
    What was the `lambda` supposed to do? You aren't calling it, and `dict()` doesn't know to call it. – jasonharper Jun 12 '20 at 15:01
  • yeah, just trying to challenge myself to see if I can put it together using a lambda. – vow7779 Jun 12 '20 at 15:02
  • `name: hero` and `names[name]: heroes[hero]`. – bipll Jun 12 '20 at 15:03
  • 1
    Lambdas in Python are a way to define functions without naming (hence storing) them - not sure that it could prove useful here. Most efficient will be using Python natives (`dict(zip())`). See https://stackoverflow.com/questions/209840/convert-two-lists-into-a-dictionary – arnaud Jun 12 '20 at 15:06

1 Answers1

0

just trying to challenge myself to see if I can put it together using a lambda

Since we've established that the lambda isn't necessary, if not down right undesirable, let's do it:

names = ['Bruce', 'Clark', 'Peter', 'Logan', 'Wade']
heroes = ['Batman', 'Superman', 'Spiderman', 'Wolverine', 'Deadpool']

l_dict = dict((lambda n, h: {name: hero for name, hero in zip(n, h)})(names, heroes))
print(l_dict)

The problem is you can't pass a lambda expression to dict(), only the result of invoking a lambda expression.

cdlane
  • 40,441
  • 5
  • 32
  • 81