简体   繁体   English

python-如果字典键等于某个值,则从列表中删除字典

[英]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) 我想知道如何在用户状态等于“脱机”且订单类型等于“购买”时从此列表中删除特定的字典(使用for循环对其进行迭代,并在迭代时修改列表,由于列表指针而导致异常)

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'}] 输出: [{'user': {'status': 'online'}, 'order_type': 'sell'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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