如果我有一个字典,并且我想删除其中值为空列表的条目,[]我将如何进行此操作?
我试过了:
for x in dict2.keys():
if dict2[x] == []:
dict2.keys().remove(x)
Run Code Online (Sandbox Code Playgroud)
但那没用.
小智 12
.keys()提供对字典中键列表的访问,但对它的更改不一定(必然)反映在字典中.您需要使用del dictionary[key]或dictionary.pop(key)删除它.
由于某些版本的Python中的行为,您需要创建一个密钥列表的副本,以便正常工作.因此,如果编写为:
for x in list(dict2.keys()):
if dict2[x] == []:
del dict2[x]
Run Code Online (Sandbox Code Playgroud)
JBe*_*rdo 10
较新版本的python支持dict理解:
dic = {i:j for i,j in dic.items() if j != []}
Run Code Online (Sandbox Code Playgroud)
这些比filter或for循环更易读
| 归档时间: |
|
| 查看次数: |
10245 次 |
| 最近记录: |