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.
CodePudding user response:
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']}