1
item1 = [{"name": "water", "color": "blue", "parts": 1}]
item2 = [
{"name": "water", "color": "blue", "parts": 1},
{"name": "water", "color": "blue", "parts": 2},
{"name": "water", "color": "blue", "parts": 3},
{"name": "water", "color": "blue", "parts": 4},
]
newItem = []

for index in range(len(item2)) :
if index == len(item1) :
    newItem = [ *item1, *item2]
print(newItem)

Output:

[{'name': 'water', 'color': 'blue', 'parts': 1}, {'name': 'water', 'color': 'blue', 'parts': 1}, {'name': 'water', 'color': 'blue', 'parts': 2}, {'name': 'water', 'color': 'blue', 'parts': 3}, {'name': 'water', 'color': 'blue', 'parts': 4}]

I want to be able to skip the first index of item2 and spread the rest into the new list, so I don't have duplicate values in the new list

Bomatebo
  • 11
  • 1
  • 1
    Does this answer your question? [Combine two dictionaries and remove duplicates in python](https://stackoverflow.com/questions/9890364/combine-two-dictionaries-and-remove-duplicates-in-python) – noah1400 Jul 17 '22 at 20:59
  • Thanks, this was very close to what i was looking for. the problem is it results to [[item1+item2]]. Concatenating the two items. I found this similar answer in this https://stackoverflow.com/questions/12433695/extract-elements-of-list-at-odd-positions/12433705#12433705 and reviewed my code. The solution is newItem = [ *item1, *item2[index:]]/code> – Bomatebo Jul 17 '22 at 21:20
  • `item2[len(item1):]`? – BeRT2me Jul 18 '22 at 06:59

1 Answers1

0

Just use variations of " if item is in X: " syntax

item1 = [{"name": "water", "color": "blue", "parts": 1}]
item2 = [
{"name": "water", "color": "blue", "parts": 1},
{"name": "water", "color": "blue", "parts": 2},
{"name": "water", "color": "blue", "parts": 3},
{"name": "water", "color": "blue", "parts": 4},
]

new_list_of_dicts= []
for dict_item in item2:  #you can just cycle through the list itself
    if dict_item not in item1:   #then compare with elements in item1
        new_list_of_dicts.append(dict_item)
print(new_list_of_dicts)

Output:

[{'name': 'water', 'color': 'blue', 'parts': 2}, {'name': 'water', 'color': 'blue', 'parts': 3}, {'name': 'water', 'color': 'blue', 'parts': 4}]
Angelo562
  • 23
  • 6