i would like to know how to combine data in multiple lists, i have combined them in a way so that they all congregate in the same [] but there are objects with the same name and different values that i want to combine the values and only have one object representing it. basically how do i combine the two "bananas" objects ?
i havent tried anything that has worked because i cant find anything specifically related to my issue, i understand that its simple i just cannot find a specific enough answer.
CodePudding user response:
You can use a dictionary to combine the values of the objects with the same name. You can iterate over the lists, and for each object, check if the name already exists in the dictionary as a key. If it does, add the value to the existing value, otherwise, add the name and value as a new key-value pair.
Here is how I would proceed :
merged = {}
lists = [fruit, items, colours]
for lst in lists:
for obj in lst:
if obj[0] in merged:
merged[obj[0]] = obj[1]
else:
merged[obj[0]] = obj[1]
print(merged)
The output will be a dictionary containing the combined values of all objects with the same name.
In your case, the merge variable is a list containing all the elements of the three lists but not combining the values of the objects with the same name.
Regarding sorting the final output, you can use the sorted() function on the dictionary items and pass a key function that sorts the items based on the key or value. This way you can sort the dictionary by key or value based on the user input.
Hope this helps!
CodePudding user response:
You can use
fruit = [['apple', 5], ['pears', 10], ['bananas', 12]]
items = [['cars', 3], ['sheets', 5], ['bananas', 8]]
colors = [['blue', 3], ['black', 5], ['orange', 8]]
merge = fruit items colors
result = set(
(item, sum(quantity for label, quantity in merge if label == item))
for item, _ in merge
)
result
Output
{('apple', 5),
('bananas', 20),
('black', 5),
('blue', 3),
('cars', 3),
('orange', 8),
('pears', 10),
('sheets', 5)}