-2
data = [{u'class': u'A'}, {u'class': u'A'}, {u'class': u'B'}]

I want to get a list with all existing class values in data. Is there any efficient way to sort out double values?

output = [{u'class': u'A'}, {u'class': u'B'}]
flowerflower
  • 327
  • 1
  • 3
  • 10

1 Answers1

0

Use a set instead of a list:

output = set(d['class'] for d in data)
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • This doesn't yield exactly what OP asked for. – Robᵩ Aug 01 '16 at 15:10
  • This gives a `KeyError`. Did you want to use `u'class'` rather htan `'value'`? And as someone else has pointed out, the result is not what is wanted. – Rory Daulton Aug 01 '16 at 15:19
  • Thank you RemcoGerlich, I like that. – flowerflower Aug 01 '16 at 21:40
  • And thank you Poke for linking, I didn't know that I should look for the words dublicate and dict. With `list(set(i['class'] for i in data))` I get `[u'A, u'B]`. And with `[dict(t) for t in set([tuple(d.items()) for d in data])]` I get `[{u'class': u'B'}, {u'class': u'A'}]` . – flowerflower Aug 01 '16 at 21:50
  • @flowerflower: you can also turn the dicts into frozendicts (same but immutable) as they can be placed into sets: `set(frozendict(d) for d in data)`. Then put `list()` around that if you want to turn it into a list again. Order isn't preserved though. – RemcoGerlich Aug 02 '16 at 07:00