I'm expecting to create the list3, grabbing the ids and then associate with each Task (list1) and remove the duplicite, but I'm not getting do it.
list1 = [
{"Name": "Richard", "Tasks":["Deadlifts","Jump"]},
{"Name": "Peter", "Tasks": ["Jump", "OverHead"]},
{"Name": "Paul", "Tasks": ["Dumbbel","Jump"]}
]
list2 = [
{"Id":1, "Exercise":["Deadlifts","Jump"]},
{"Id":2, "Exercise":["Deadlifts"]},
{"Id":3, "Exercise":["Dumbbel"]},
{"Id":4, "Exercise":["OverHead","Jump"]},
{"Id":5, "Exercise":["Deadlifts","Jump"]},
{"Id":6, "Exercise":["Jump","Dumbbel","OverHead"]},
]
grabId = {}
for i in list2:
for k in i["Exercise"]:
grabId.setdefault(k,[]).append(i["Id"])
# {'Deadlifts': [1, 2, 5], 'Jump': [1, 4, 5, 6], 'Dumbbel': [3, 6], 'OverHead': [4, 6]}
What I'm expecting...
list3 = [
{"Name": "Richard", "Tasks":["Deadlifts","Jump"], "Ids":[1,2,4,5,6]},
{"Name": "Peter", "Tasks": ["Jump", "OverHead"], "Ids":[1,3,4,5,6]},
{"Name": "Paul", "Task": ["Dumbbel","Jump"], "Ids":[1,3,4,5,6]}
]
CodePudding user response:
I hope I've understood your question well:
list1 = [
{"Name": "Richard", "Tasks": ["Deadlifts", "Jump"]},
{"Name": "Peter", "Tasks": ["Jump", "OverHead"]},
{"Name": "Paul", "Tasks": ["Dumbbel", "Jump"]},
]
list2 = [
{"Id": 1, "Exercise": ["Deadlifts", "Jump"]},
{"Id": 2, "Exercise": ["Deadlifts"]},
{"Id": 3, "Exercise": ["Dumbbel"]},
{"Id": 4, "Exercise": ["OverHead", "Jump"]},
{"Id": 5, "Exercise": ["Deadlifts", "Jump"]},
{"Id": 6, "Exercise": ["Jump", "Dumbbel", "OverHead"]},
]
tmp = {}
for d in list2:
for e in d["Exercise"]:
tmp.setdefault(e, []).append(d["Id"])
list3 = [
{**d, "Ids": sorted(set(i for t in d["Tasks"] for i in tmp[t]))}
for d in list1
]
print(list3)
Prints:
[
{"Name": "Richard", "Tasks": ["Deadlifts", "Jump"], "Ids": [1, 2, 4, 5, 6]},
{"Name": "Peter", "Tasks": ["Jump", "OverHead"], "Ids": [1, 4, 5, 6]},
{"Name": "Paul", "Tasks": ["Dumbbel", "Jump"], "Ids": [1, 3, 4, 5, 6]},
]
CodePudding user response:
Sometimes its a good idea to break the task into manageable pieces and test them first:
def get_ids(exercises):
exercises = set(exercises)
return list(set(d["Id"] for d in list2 if
exercises.intersection(d["Exercise"])))
assert(get_ids(["Jump"]) == [1, 4, 5, 6])
assert(get_ids(["Deadlifts", "Jump"]) == [1, 2, 4, 5, 6])
Now put it all together:
for person in list1:
person["Ids"] = get_ids(person["Tasks"])
print(list1)
[{'Name': 'Richard', 'Tasks': ['Deadlifts', 'Jump'], 'Ids': [1, 2, 4, 5, 6]}, {'Name': 'Peter', 'Tasks': ['Jump', 'OverHead'], 'Ids': [1, 4, 5, 6]}, {'Name': 'Paul', 'Tasks': ['Dumbbel', 'Jump'], 'Ids': [1, 3, 4, 5, 6]}]