Home > OS >  Getting a distinct list of values from a list of dicts
Getting a distinct list of values from a list of dicts

Time:01-18

I have a list of dicts like this:

[{'value': 'apple', 'blah': 2}, 
 {'value': 'banana', 'blah': 3} , 
 {'value': 'banana', 'blah': 4}]

I want distinct data on the basis of one field for eg 'value' so I want this output ['apple', 'banana']

What is the best way to do this?

CodePudding user response:

Have you tried to use this piece of code?

list(set(element.get('value') for element in input_collection))

Or even it would be good to apply suggestion of @csjh

list(set(element['value'] for element in input_collection if 'value' in element))

CodePudding user response:

We could try set comprehension (added if condition in case 'value' key doesn't exist, thanks @0x263A):

out = list({d['value'] for d in lst if 'value' in d})

If order is important, we can also use dict.fromkeys:

out = list(dict.fromkeys([d['value'] for d in lst if 'value' in d]).keys())

Output:

['apple', 'banana']

CodePudding user response:

ls = list(ld[0].values()) list(ld[1].values()) list(ld[0].values()) res = [ls[0],ls[2]]

  •  Tags:  
  • Related