When user adding details to a dictionary, I want check those details are already there or not,
When name, age, team and car have same values in another record ignore those inputs and tell the user "It's already there" otherwise "add" details to the dictionary. Also, this duplication check should happen before appending to the List.
I don't how to do this I tried but it doesn't work
driver_list = []
name = str(input("Enter player name : "))
try:
age = int(input("Enter the age : "))
except ValueError:
print("Input an integer",)
age = int(input("Enter the age : "))
team = str(input("Enter team name : "))
car = str(input("Enter name of the car : "))
try:
current_points = int(input("Enter the current points of the player : "))
except ValueError:
print("Input an integer")
current_points = int(input("Enter the current points of the player : "))
driver_details={"Name":name ,"Age": age,"Team": team ,"Car": car, "Current_points": current_points}
driver_list.append(driver_details)
CodePudding user response:
Can you use a set()
instead of a list()
? it will ensure deduplication
driver_list = set()
Additionally, if you have more specific requirements (such as a unique name, or rather not every field in your dict, but a subset of them), pack them into a sub-dict and keep that in a set to compare
driver_list_unique = set()
driver_list = list()
name = input("name: ")
inner = input("inner: ")
outer = input("other: ")
cmp = {
"name": name,
"inner": inner,
}
if cmp in driver_list_unique:
return
driver_list_unique.add(cmp)
cmp.update({
"outer": outer,
})
driver_list.append(cmp)
CodePudding user response:
# check all values in the driver_det is found in any of the
# dictionaries in the list driver_list
def checkAllInList(driver_det):
# define the keys we are interested in
Interest = ['name', 'age', 'team', 'car']
# get corresponding values from the driver_det
b = set([value for key, value in driver_det.items() if key in Interest])
# iterate over all driver_list dictionaries
for d in driver_list:
# get all values corresponding to the interest keys for the d driver
a = set([value for key, value in d.items() if key in Interest])
# if both have the same values, return true
if a == b:
return True; # if found equal, return true
return False; #otherwise, return false if non of the dictionaries have these details
# you can use it like that
if checkAllInList(driver_details): # check a duplicate is found
print("this is a duplicate value")
else: # no duplicate found
driver_list.append(driver_details)