I have a question regarding inverse filtering in dictionary. I have a dictionary as:
dico = {
Pierre:{
'Math':16,
'Chimie':09,
'Dessin':18,
'Electronic':20,
'Info':14,
}
Jean:{
'Physics':10,
'Chimie':20,
'Dessin':13,
'Electronic':16,
'Info':17,
}
Giovani:{
'Math':16,
'Physics':14,
'Chimie':13,
'Dessin':14,
'Electronic':17,
'Info':12,
}
...
}
What I want is to extract all the student which attempt each exam, and have output as set or list such as:
'Math': [pierre,Giovanie], 'Physics': [Jean, Giovanie]
exam_set = [{k:v for (k, v) in i.items()}
for i in dico if i.get(v) != 0]
But is doesn't work and I don't know how to how to fix that.
CodePudding user response:
Try:
dct = {
"Pierre": {
"Math": 16,
"Chimie": 9,
"Dessin": 18,
"Electronic": 20,
"Info": 14,
},
"Jean": {
"Physics": 10,
"Chimie": 20,
"Dessin": 13,
"Electronic": 16,
"Info": 17,
},
"Giovani": {
"Math": 16,
"Physics": 14,
"Chimie": 13,
"Dessin": 14,
"Electronic": 17,
"Info": 12,
},
}
out = {}
for k, v in dct.items():
for i in v:
out.setdefault(i, []).append(k)
print(out)
Prints:
{
"Math": ["Pierre", "Giovani"],
"Chimie": ["Pierre", "Jean", "Giovani"],
"Dessin": ["Pierre", "Jean", "Giovani"],
"Electronic": ["Pierre", "Jean", "Giovani"],
"Info": ["Pierre", "Jean", "Giovani"],
"Physics": ["Jean", "Giovani"],
}
Or if you want sets:
out = {}
for k, v in dct.items():
for i in v:
out.setdefault(i, set()).add(k)
Prints:
{
"Math": {"Giovani", "Pierre"},
"Chimie": {"Jean", "Giovani", "Pierre"},
"Dessin": {"Jean", "Giovani", "Pierre"},
"Electronic": {"Jean", "Giovani", "Pierre"},
"Info": {"Jean", "Giovani", "Pierre"},
"Physics": {"Jean", "Giovani"},
}
CodePudding user response:
i commented everything play with the code so you can get better at python
students = { # students
"Pierre":{
'Math':16,
'Chimie':90,
'Dessin':18,
'Electronic':20,
'Info':14,
},
"Jean":{
'Physics':10,
'Chimie':20,
'Dessin':13,
'Electronic':16,
'Info':17,
},
"Giovani":{
'Math':16,
'Physics':14,
'Chimie':13,
'Dessin':14,
'Electronic':17,
'Info':12,
}
}
data = {} # create data dict
for student in students: # loop to every student
for exam in students[student]: # loop in the student exams
if exam in data: # check if exam list exist
data[exam].append(student) # append to the exam list
else: # else create an exam list
data[exam] = [student] # create and add the student to the exam list
print(data) # let see the result
CodePudding user response:
defaultdict can handle this very easily
from collections import defaultdict
def solution(dic):
res = defaultdict(list)
for k, v in students.items():
for k2, v2 in v.items():
res[k2].append(k)
return dict(res)
print(solution(dico))
OUTPUT:
{'Math': ['Pierre', 'Giovani'], 'Chimie': ['Pierre', 'Jean', 'Giovani'], 'Dessin': ['Pierre', 'Jean', 'Giovani'], 'Electronic': ['Pierre', 'Jean', 'Giovani'], 'Info': ['Pierre', 'Jean', 'Giovani'], 'Physics': ['Jean', 'Giovani']}