Ad
How To Return A Value If It Is Found In The List
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad