0

I have a list of dictionaries like this:

s = [{'a':1,'b':2},{'a':3},{'a':2},{'a':1}]

remove duplicate value pair and I want a list of dictionaries like:

s = [{'a':1},{'a':3},{'a':2}]

4 Answers4

2

Use list comprehension with filter a:

s = [{k: v for k, v in x.items() if k =='a'} for x in s]
print (s)
[{'a': 1}, {'a': 3}, {'a': 2}]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

You could use a list comprehension adding new dictionary entries only if 'a' is contained:

[{'a':d['a']} for d in s if 'a' in d]
# [{'a': 1}, {'a': 3}, {'a': 2}]
yatu
  • 86,083
  • 12
  • 84
  • 139
2

You can try this.

s = [{'a':1,'b':2},{'a':3},{'a':2}]
s=[{'a':d['a']} for d in s]
# [{'a': 1}, {'a': 3}, {'a': 2}]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

If you want to have a list of singleton dictionaries with only a keys, you can do this:

>>> [{'a': d.get('a')} for d in s]
[{'a': 1}, {'a': 3}, {'a': 2}]

But this just seems more suitable for a list of tuples:

>>> [('a', d.get('a')) for d in s]
[('a', 1), ('a', 3), ('a', 2)]

From the docs for dict.get:

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a Key Error.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75