如果其中一个键中包含字符,如何删除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"
}]
答案 0 :(得分:1)
在迭代时从列表中删除元素的正确方法是在列表的副本上进行迭代:这样一来,您不会得到意想不到的结果,因为您没有在编辑要迭代的列表。
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)
答案 1 :(得分:0)
尝试一下:
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)
答案 2 :(得分:0)
您也可以尝试
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将具有过滤的项目列表。然后,以后可以根据需要将其重新分配给词典。
答案 3 :(得分:0)
具有此初始指示:
list = {
'results': [
{'marque': 'samsung', 'price_str': 'results awaited'},
{'marque': 'apple', 'price_str': 'sold'}
]
}
通过使用filter(),您可以从列表中获取适合您条件的元素。在您的情况下,您还可以使用find()函数来获得不适合您搜索的结果,因此您将获得所需的数组:
>>> new_results = filter(lambda x: x['price_str'].lower().find("await") < 0, list["results"])
>>> new_results
[{'marque': 'apple', 'price_str': 'sold'}]
>>> list["results"] = new_results
>>> list
{'results': [{'marque': 'apple', 'price_str': 'sold'}]}
希望有帮助!