![]() |
Compare dictionaries in list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Compare dictionaries in list (/thread-10011.html) |
Compare dictionaries in list - vaison - May-08-2018 Hello, I have a list of dictionaries and I need to compare some values of all of them. I only need to know if all of the comparison values are different or not. I need to know if any 'name' in the dictionaries is repeated: l1 = [{'name': 'n3', 'count':1, 'other':0}, {'name': 'n2', 'count':2}, {'name': 'n3', 'count':3, 'other': 0, 'other2':25 }]The answer in this case is "Yes" because the first and the third dictionaries in the list has the same 'name'. I try to get the dict values that I need to compare in lists, and then realize the comparative. But not work: names = [l1[i]['name'] for i in range(len(l1))]I'm practicing my English to improve it. Then, I hope that I explained it well. To consider: - Initially, I don't know how many elements are in the list l1. The solution should work with any amount of dictionaries. - The keys of the items to compare ('name' in this case) exists in all the dictionaries in the list Is there a compact way to make this comparison, which can be used for lists with any number of dictionaries? Thanks! RE: Compare dictionaries in list - killerrex - May-08-2018 Use a set that will collect only the different values: names = {d['name'] for d in l1} if len(names) == len(l1): print("All the names are different!") else: print("At least one name is repeated") RE: Compare dictionaries in list - vaison - May-10-2018 Hi killerrex, Great! Thanks a lot. |