Python coverting list to dictionary -
i trying write function takes list of strings containing names , marks parameter. , return dictionary of (mark, [list of names got mark])
example:
def example(["john,5", "jessica,5", "jack,7"]):
returns:
{'5' : ["john", "jessica"], '7' : "jack"}
i find tricky problem... how solve using split(',')
this i've done far:
def create_marks_dict(my_list): dictionary = {} name in my_list: if name not in dictionary: dictionary[name] return dictionary
you'll need use defaultdict collections use lists in dictionary
from collections import defaultdict def create_marks_dict(my_list): dictionary = defaultdict(list) item in my_list: name, marks=item.split(',') dictionary[marks].append(name) return dictionary
output:
{'5' : ["john", "jessica"], '7' : "jack"}
if output of dict
required instead of defaultdict
, can cast dictionary
while returning
return dict(dictionary)
Comments
Post a Comment