Ad

How To Return A Value If It Is Found In The List

- 1 answer

I am trying to find some value in the nested list, and if it is present, I want to return a particular field as my output.

This is my input list:

set1 = [
    {'type': 'customer',  'value': '93227729', 'field': '1Ax6EsCM'},
    {'type': 'customer', 'value': '1234', 'field': 'abc'},
    {'type': 'customer', 'value': '78654', 'field': 'abc'}
]

I want to find the word 'abc' in this list, and if it present, then I want to output the corresponding "value" attribute. In case multiple values are found, the output should be a concatenation of all corresponding values, with commas.

In the above list, after searching 'abc', the output I need is: 1234,78654

I have tried for and if operators, but the code is returning all of the values:

set1 = [
    {'type': 'customer',  'value': '93227729', 'field': '1Ax6EsCM'}, 
    {'type': 'customer', 'value': '1234', 'field': 'abc'},
    {'type': 'customer', 'value': '78654', 'field': 'abc'}
]
print(set1)
val ='abc'

for data in set1:
    if (val in g for g in data):
        print(data['value'])

Ad

Answer

Use a list-comprehension:

[x['value'] for x in set1 if x['field'] == search_word]

Example:

set1 = [{'type': 'customer',  'value': '93227729', 'field': '1Ax6EsCM'}, {'type': 'customer', 'value': '1234', 'field': 'abc'},{'type': 'customer', 'value': '78654', 'field': 'abc'}]
search_word = 'abc'

print([x['value'] for x in set1 if x['field'] == search_word])
# ['1234', '78654']
Ad
source: stackoverflow.com
Ad