Apr-08-2020, 07:45 PM
(This post was last modified: Apr-09-2020, 04:38 AM by deanhystad.)
Was I understanding the problem wrong the entire time? In an early post you said this:
"If If the list has a number of key "numero" duplicated, it does not create a new dict. New dict is only available when all values of key "numero" are unique."
and this:
"yes, it return an empty dic."
I interpreted that as:
If numero is unique for each item in list
return dictionary made from list
else
return empty dictionary
Now it sounds like what you want is:
If numero is unique for each item in list
add items to existing dictionary
To do that you need to test the entire list first and only add entries if the list passes the uniqueness test.
"If If the list has a number of key "numero" duplicated, it does not create a new dict. New dict is only available when all values of key "numero" are unique."
and this:
"yes, it return an empty dic."
I interpreted that as:
If numero is unique for each item in list
return dictionary made from list
else
return empty dictionary
Now it sounds like what you want is:
If numero is unique for each item in list
add items to existing dictionary
To do that you need to test the entire list first and only add entries if the list passes the uniqueness test.
f = [ {"numero":"20202020","name" : "Durand", "first":"Martin", "notes":[15,15.5,8,13]}, {"numero":"21212121","name" : "Dupond", "first":"Alain", "notes":[11,9.5,5.5,18]}, {"numero":"28790020","name" : "Férien", "first":"Mélissa", "notes":[13,19.5,15,8]}, {"numero":"20212021","name" : "Bosse", "first":"Mélissa", "notes":[13,19.5,15,8]}, {"numero":"21202120","name" : "Allard", "first":"Chloé", "notes":[11,9.5,2,17]}, {"numero":"29019022","name" : "Durand", "first":"Alan", "notes":[12,15.5,8,13]}, ] g = [ {"numero":"20202020","name" : "Durand", "first":"Martin", "notes":[15,15.5,8,13]}, {"numero":"21212121","name" : "Dupond", "first":"Alain", "notes":[11,9.5,5.5,18]}, {"numero":"28790020","name" : "Férien", "first":"Mélissa", "notes":[13,19.5,15,8]}, {"numero":"20212021","name" : "Bosse", "first":"Mélissa", "notes":[13,19.5,15,8]}, {"numero":"21202120","name" : "Allard", "first":"Chloé", "notes":[11,9.5,2,17]}, {"numero":"29019022","name" : "Durand", "first":"Alan", "notes":[12,15.5,8,13]}, {"numero":"21212121","name" : "Dupond", "first":"Alain", "notes":[11,9.5,5.5,18]}, ] new_dict = {} def add(seq): """Add items in seq to new_dict ONLY if every item in seq is unique""" # Test list for uniqueness for i in range(len(seq)-1): for j in range(i+1, len(seq)): if seq[i]['numero'] == seq[j]['numero']: print("Numero en double!\n " + "----> " + seq[i]['numero'] + " \n Fichier non utilisable!") return new_dict # Return unaltered dictionary # seq is ok. Add items to dictionary for i in seq: (key, value), *rest = i.items() new_dict[value] = dict(rest) return new_dict print(add(f)) print(add(g))