0

I'm currently in the learning stage of Python. My aim is to use lambda function to arrange list on the length of names and store results in dictionary with length as key and value as names

names = ['Alan', 'Bradman', 'Adan', 'Albert', 'West', 'Will', 'Steven']

len_sorted = sorted(names, key=lambda x: len(x))

result = dict(lambda x: (result[len(val)], [val]) if len(val) not in result.keys() else result[len(val)].append(val) for val in len_sorted)

But, it is creating the following error.

TypeError                                 Traceback (most recent call last)
/home/amartya/DAV/practical1.ipynb Cell 10 in <cell line: 5>()
      1 len_sorted = sorted(names, key=lambda x: len(x))
      2 len_sorted
----> 5 result = dict(lambda x: (result[len(val)], [val]) if len(val) not in result.keys() else result[len(val)].append(val) for val in len_sorted)
      7 result

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

I have gone through several other StackOverflow questions related to it. But, I'm not able to figure it out.

1
  • Side note: do not use a lambda when you have a function already: len_sorted = sorted(names, key=len) Commented Aug 5, 2022 at 10:01

1 Answer 1

1

You want to create a dictionary, but you wrote (result[len(val)], [val]) is a tuple. Use this

names = ['Alan', 'Bradman', 'Adan', 'Albert', 'West', 'Will', 'Steven']

len_sorted = sorted(names, key=lambda x: len(x))
results = dict()
apply_func = lambda x: results.update({len(x): [x]} if len(x) not in results.keys() else {len(x): results[len(x)] + [x]})
[apply_func(ele) for ele in len_sorted]
print(results)

And the output result

{4: ['Alan', 'Adan', 'West', 'Will'], 6: ['Albert', 'Steven'], 7: ['Bradman']}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.