0

I need to choose all active users with the easiest way

users = [{'id': 1, 'active': False}, {'id': 2, 'active': True}, {'id': 3, 'active': True}, {'id': 4, 'active': True}, {'id': 5, 'active': True}, {'id': 6, 'active': True}]
kenzo
  • 29
  • 1
  • 5

4 Answers4

2

You could do that with list comprehension,

active_users = [user for user in users if user['active']]
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
2

Using a list comprehension would work fine:

users = [user for user in users if user['active']]
aumo
  • 5,344
  • 22
  • 25
2

Use filter. It will return a list in py2.x and a generator for py3.x

filter(lambda x:x['active'], users)
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • For anybody looking for a discussion of "should I use a list comprehension or filter": https://stackoverflow.com/questions/3013449/list-filtering-list-comprehension-vs-lambda-filter –  Sep 18 '17 at 13:16
  • `x['active']` not `x['xctive']` – Aamir Rind Sep 18 '17 at 13:17
0
active_user = [user['id']  for user in users if user['active']]
bfontaine
  • 18,169
  • 13
  • 73
  • 107
im_w0lf
  • 144
  • 3