Question feels like it's phrased poorly, feel free to adjust it if you agree and know how better to phrase it.
I have the following code:
def owned_calendars(cal_items):
"""Returns only the calendars in which the user is marked as "owner"
"""
owner_cals = []
for entry in cal_items:
if entry['accessRole'] == "owner":
owner_cals.append(cal_items[cal_items.index(entry)])
return owner_cals
cal_items
is a list
of dictionaries
In the line where I have written owner_cals.append(cal_items[cal_items.index(entry)])
I'm trying to append the dictionaries that have the property accessRole = owner
.
The line just seems super long and clunky, and I'm wondering if there's an easier/more intuitive way to do it?
Try this. You can do this in one line using list comprehension .
owner_cals = [x for x in cal_items if x["access_role"]=="owner"]
You can also use enumerate
method.
owner_cals = [j for i,j in enumerate(cal_items) if j["access_role"]=="owner"]
Also, remember .index()
returns the lowest index where item is found .
["foo", "bar", "baz", "bar"].index("bar")
will always return 1.
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.