Home > Blockchain >  is there a way to only have a value in a list if the key appears multiple times in a file?
is there a way to only have a value in a list if the key appears multiple times in a file?

Time:09-16

I'm trying to make a dictionary from items in a file. What I have now works but I was wondering if there is a way to only have a list if the key is a duplicate that has different value.so, if I have this

micheal math 2
jim chem 3 
jim math 3
pam cs 4

expected output: {micheal:[math,2],jim: [[chem,3], [math,3]], pam: [cs,4]}

actual output: {micheal:[[math,2]],jim: [[chem,3], [math,3]], pam: [[cs,4]]}

current code:

example_dict = {}
for line in dictionary:
     line = (line.strip()).split(' ')
     key = line[0]
     if key not in example_dict
         example_dict[key] = []
     example_dict[key].append(line[1:])
return example_dict

CodePudding user response:

With your current solution, go over your example_dict afterward and flatten values that only have one element, e.x.:

...

example_dict = {k: (v if len(v) > 1 else v[0]) for k, v in example_dict.items()}
return example_dict

CodePudding user response:

It seems like it would make a lot of sense to use dictionaries instead of tuple lists as values.

example_dict = {}
for line in dictionary:
    name, subject, grade = line.strip().split() # optional, but cleaner
    if name not in example_dict:
        example_dict[name] = {}
    example_dict[name][subject] = grade

Result:

{'micheal': {'math': '2'},
 'jim': {'chem': '3', 'math': '3'},
 'pam': {'cs': '4'}}
  • Related