Reputation: 43
I want to get something like this:
{'eve': [19, 50, 'fail'], 'walle': [79, 65, 'pass'], 'sandy': [28, 49, 'fail'],'bob': [15, 60, 'pass']}
What I tried to achieve this is:
def try_dic_from_list(names, ages, scores):
for s in scores:
p= "pass" if s >=60 else "fail"
mydict={key:value for key,value in list(zip(names,zip(ages,scores,str(p))))}
print(mydict)
print(try_dic_from_list(["walle", "sandy", "eve", "bob"], [79, 28, 19, 15],
[65, 49, 50, 60]))
This outputs this:
{'walle': (79, 65, 'p'), 'sandy': (28, 49, 'a'), 'eve': (19, 50, 's'), 'bob': (15, 60, 's')}
Any suggestions to get the square brackets instead of parenthesis and also how can I achieve the string in the list that pass or fail. Thank you.
Upvotes: 0
Views: 119
Reputation: 390
The indentation inside the function seems to be the biggest problem, specifically the fact that it loops over the scores and only sets a final value for p
at the end. You need some way to store the passes and fails for each score, not just the last one.
The mydict
line is also really muddled and I struggle to make much out of it (so will another developer who reads this and yourself when you read this three months from now).
I've rewritten it so it works and looks a bit more sane:
def try_dic_from_list(names, ages, scores):
pees = []
for s in scores:
p= "pass" if s >=60 else "fail"
pees.append(p)
values = [list(x) for x in zip(ages, scores, pees)]
final_zip = zip(names, values)
dict = {key:value for key,value in final_zip}
return dict
If you're concerned about performance, you can certainly reduce the number of comprehensions made, but this is at least more readable and easier to debug.
Upvotes: 0
Reputation: 1669
Saying what you need to do on one line, this gives:
def try_dic_from_list(names, ages, scores):
return {name: [age, score, "pass" if score >= 60 else "fail"] for name, age, score in zip(names, ages, scores)}
print(try_dic_from_list(["walle", "sandy", "eve", "bob"], [79, 28, 19, 15],
[65, 49, 50, 60]))
# {'bob': [15, 60, 'pass'], 'walle': [79, 65, 'pass'], 'eve': [19, 50, 'fail'], 'sandy': [28, 49, 'fail']}
Upvotes: 1
Reputation: 1121924
You are zipping the last pass
or fail
string with other values, so it is seen as a sequence of characters to zip.
Zip first, then include a pass
or fail
:
def try_dic_from_list(names, ages, scores):
return {name: [age, score, 'pass' if score >= 60 else 'fail']
for name, age, score in zip(names, ages, scores)}
Demo:
>>> def try_dic_from_list(names, ages, scores):
... return {name: [age, score, 'pass' if score >= 60 else 'fail']
... for name, age, score in zip(names, ages, scores)}
...
>>> try_dic_from_list(["walle", "sandy", "eve", "bob"], [79, 28, 19, 15], [65, 49, 50, 60])
{'bob': [15, 60, 'pass'], 'sandy': [28, 49, 'fail'], 'eve': [19, 50, 'fail'], 'walle': [79, 65, 'pass']}
Upvotes: 2