My list looks like as follows:
list = [{u'Value': u'Value1', u'Key': u'Key1'}, {u'Value': u'value2', u'Key': u'key2'}]
I would like to retrieve value1, but only if key1 matches a specific string, i'm not sure if i have to iterate over this twice???
You can add a guard to a list comprehension to act as a filter
[d[u"Value"] for d in list if d[u"Key"] == u"Key1"]
You should also avoid shadowing built in names like list
No, you don't need to iterate over the list twice:
value = None
for d in list:
if d[u"Key"] == u"Key1":
value = d[u"Value"]
This can be written in one line using next()
and a generator:
value = next((d[u"Value"] for d in list if d[u"Key"] == u"Key1"), None)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.