简体   繁体   中英

python - remove a dictionary from a list if dictionary key equals a certain value

i want to know how to remove a specific dict from this list if user status equals "offline" and order type equals "buy" (iterating over it with for loop and modifying the list while iterating produces an exception because of the list pointer)

mylist = [
           {
             "user": {"status": "offline"}, 
             "order_type": "buy"
           },
           {
             "user": {"status": "online"},
             "order_type": "sell"
           }
         ]

You can re-create the list without undesired elements:

mylist = [key_values for key_values in mylist if key_values['user']['status'] != 'offline']

(*) do not name your variables using reserved keywords.

seq = [
         {
           "user": {"status": "offline"}, 
           "order_type": "buy"
         },
         {  "user": {"status": "online"},
            "order_type": "sell"
         }
       ]

for _ in seq:
    print _
    if _['user']['status'] == 'offline':
        seq.remove(_)

print seq

In case if you're looking for in place removal.

output: [{'user': {'status': 'online'}, 'order_type': 'sell'}]

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