简体   繁体   中英

Is there a better way in python to compare dictionaries in different list?

x = [{'name': 'Abhay', 'has_subscription': True, 'id': 1}, {'name': 'Jay', 'has_subscription': True, 'id': 2}, {'name': 'John', 'has_subscription': True, 'id': 3}]
y = [{'name': 'John', 'id': 0}, {'name': 'Abhay', 'id': 1}, {'name': 'Jay','id': 2}, {'name': 'John', 'id': 3}, {'name': 'Chanakya', 'id': 4}]

I want to get all the items from 'y' which are not in x

I have tried some solutions but I don't think they are optimised to deploy on production server

this is the code that I've tried

for user in y :
   for xuser in x:
      if user['id'] == xuser['id']:
         y.remove(user)
         break
print(y)

And now I have users without active_subscription that is in 'y'

One way to do it that avoids repeatedly scanning x :

>>> x = [{'name': 'Abhay', 'has_subscription': True, 'id': 1}, {'name': 'Jay', 'has_subscription': True, 'id': 2}, {'name': 'John', 'has_subscription': True, 'id': 3}]
>>> y = [{'name': 'John', 'id': 0}, {'name': 'Abhay', 'id': 1}, {'name': 'Jay', 'id': 2}, {'name': 'John', 'id': 3}, {'name': 'Chanakya', 'id': 4}]
>>> xk = set(d["id"] for d in x)
>>> ym = [d for d in y if d["id"] not in xk] 
>>> ym
[{'name': 'John', 'id': 0}, {'name': 'Chanakya', 'id': 4}]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM