Home > Software engineering >  How to get unique values from one key in a dictionary
How to get unique values from one key in a dictionary

Time:09-28

I'm looking to get unique values contained in 'Class'. So the desired output is: Physics, Math. Here is a sample of my dictionary.

[(0,
  {'Number': '4732',
   'Name': 'Bob',
   'Class': 'Physics'}),
 (1,
  {'Number': '8373',
   'Name': 'Mary',
   'Class': 'Math'})]

CodePudding user response:

You can use set-comprehension:

lst = [
    (0, {"Number": "4732", "Name": "Bob", "Class": "Physics"}),
    (1, {"Number": "8373", "Name": "Mary", "Class": "Math"}),
]

out = {d["Class"] for _, d in lst}
print(*out, sep=", ")

Prints:

Physics, Math
  • Related