Python Forum
Compare dictionaries in list
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compare dictionaries in list
#1
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!
Reply
#2
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")
Reply
#3
Hi killerrex,

Great! Thanks a lot.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  Access list of dictionaries britesc 4 1,027 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  Compare two Excel sheets with Python and list diffenrences dmkfon 1 14,487 Oct-09-2021, 03:30 PM
Last Post: Larz60+
  function that returns a list of dictionaries nostradamus64 2 1,698 May-06-2021, 09:58 PM
Last Post: nostradamus64
  convert List with dictionaries to a single dictionary iamaghost 3 2,800 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,195 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  Help accessing elements of list of dictionaries Milfredo 6 2,783 Sep-07-2020, 01:32 AM
Last Post: Milfredo
  Accessing values in list of dictionaries pythonnewbie138 2 2,083 Aug-02-2020, 05:02 PM
Last Post: pythonnewbie138
  Compare response and name list in experiment knoxvillerailgrind 3 2,170 Jul-26-2020, 12:23 PM
Last Post: deanhystad
  how does .join work with list and dictionaries gr3yali3n 7 3,231 Jul-07-2020, 09:36 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020