my task was to define a function that takes a list of names and returns a dictionary of names the corresponding length of each string (Name). The code worked just fine:
def toDict(namelist):
lengths = []
for i in namelist:
lengths.append(len(i))
namedict = dict(zip(namelist, lengths))
return namedict
print(namedict)
However, 2nd part of the task was to do it in one line only and I'm getting stuck a bit there... please help.
CodePudding user response:
One approach is to use a dict
comprehension:
namedict = {name: len(name) for name in namelist}
If you need your entire function definition to be on one line, I’d suggest using a lambda:
to_dict = lambda name_list: {n: len(n) for n in name_list}
As mentioned in the comments, even though I personally prefer the lambda approach - and though I feel it’s a solid use case for it - it’s still possible to use a def
and have a normal function on a single line; you’ll just need to put the body immediately after the colon :
as shown below.
def to_dict(name_list): return {n: len(n) for n in name_list}
CodePudding user response:
Another way:
>>> li = ['one', 'three', 'four']
>>> dict(zip(li, map(len, li)))
{'one': 3, 'three': 5, 'four': 4}
How it works:
map
applies the functionlen
to each element inli
zip
forms a tuple of name and lengthdict
takes the tuple and forms a dictionary.