John
John

Reputation: 971

Adding unique dictionary to list

I have a list of dictionaries and I want to add further dictionaries to that list if they don't already exist in the list.

listofdictionary= []
newdictionary = {'Id': '001', 'Name': 'book title'}

for mydict in self.listofdictionary:
    if mydict['Id'] == newdictionary['Id']:
        print("Match for {0}".format(neworder['Title']))
    elif mydict['Id'] != newdictionary['Id']:
        self.listofdictionary.append(newdictionary)

However, if I add a second, third and forth dictionary entry I end up with...

for mydict in self.listofdictionary:
    print("{0}".format(mydict))

{'Id': '001', 'Title': 'book title'}
{'Id': '002', 'Title': 'book title'}
{'Id': '002', 'Title': 'book title'}
{'Id': '003', 'Title': 'book title'}
{'Id': '003', 'Title': 'book title'}
{'Id': '003', 'Title': 'book title'}
{'Id': '004', 'Title': 'book title'}
{'Id': '004', 'Title': 'book title'}
{'Id': '004', 'Title': 'book title'}
{'Id': '004', 'Title': 'book title'}

Thanks,

John.

Upvotes: 0

Views: 409

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

Your code checks all dictionaries in the list, and for each of the dictionaries with a different Id, it appends the new dictionary.

So if you have four dictionaries with a different Id already in the list, the new one is added four times.

Instead do

if all(olddict['Id'] != newdictionary['Id'] for olddict in self.listofdictionary):
   self.listofdictionary.append(newdictionary)

or

if newdictionary['Id'] not in [d['Id'] for d in self.listofdictionary]:
   self.listofdictionary.append(newdictionary)

If it were actually a dict of dictionaries, things'd be easier:

if newdictionary['Id'] not in self.dictofdictionaries:
    self.dictofdictionaries[newdictionary['Id']] = newdictionary

Or with multiple fields to check uniqueness with:

key = tuple(newdictionary[k] for k in ('Id', 'author', 'subject', 'etc'))

if key not in self.dictofdictionaries:
    self.dictofdictionaries[key] = newdictionary

Upvotes: 2

Related Questions