Reputation: 3
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'])
Upvotes: 0
Views: 1182
Reputation: 1622
Another solution, maybe less elegant and smart than that of Austin, is:
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 data['field'] == val:
print(data['value'])
Or you can define a list and add the various elements to it:
tmp = []
val ='abc'
for data in set1:
if data['field'] == val:
tmp.append(data['value'])
print(tmp)
#output: ['1234', '78654']
Upvotes: 0
Reputation: 26039
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']
Upvotes: 3