如果键值中的字符串

2024-09-27 07:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

如果其中一个键中有字符,如何删除JSON中列表的字典:

for i in data:
    results = i["results"]
    if not results == []:
        for x in results:
        price_str = x["price_str"]
        if "await" in price_str:
            results.remove(x)

我的意见:

"results": [{
  "price_str": "results awaited",
  "marque": "samsung"
  },
  {
  "price_str": "sold",
  "marque": "apple"
  }]

我想要的输出:

"results":[{
  "price_str": "sold",
  "marque": "apple"
  }]

Tags: injsonapple列表fordataif字典
3条回答

迭代时从列表中删除元素的正确方法是迭代列表的副本:这样做不会得到意外的结果,因为您没有编辑正在迭代的列表。你知道吗

data = {
    "results": [{
            "price_str": "results awaited",
            "marque": "samsung"
        }, {
            "price_str": "sold",
            "marque": "apple"
        }
    ]
}

for results in data.itervalues():

    # You don't need to check if the list is empty
    # The for loop doesn't start if the list is empty
    # if not results == []:

    # Iterates over a copy of the list. So when you modify the original
    # list, you do not modify the copy that you iterate over.
    for result in results[:]:
        price_str = result["price_str"]
        if "await" in price_str:
            results.remove(result)

print(data)

你也可以试试这个

dct = {'results' : [{
  "price_str": "results awaited",
  "marque": "samsung"
  },
  {
  "price_str": "sold",
  "marque": "apple"
  }]}


items = dct['results']
y=[a for a in items if "await" not in a['price_str']]

y将具有已筛选的项目列表。如果你想的话,以后你可以把它重新分配到字典里。你知道吗

试试这个:

dct = {'results' : [{
  "price_str": "results awaited",
  "marque": "samsung"
  },
  {
  "price_str": "sold",
  "marque": "apple"
  }]}

for entry, x in enumerate(dct['results']):
    if 'await' in x['price_str']:
        print(x)
        dct['results'].pop(entry)

相关问题 更多 >

    热门问题