如何从python中的字典中删除所有0?

Jet*_*ett 1 python dictionary

可以说我有一个这样的字典:

{'1': 2, '0': 0, '3': 4, '2': 4, '5': 1, '4': 1, '7': 0, '6': 0, '9': 0, '8': 0}
Run Code Online (Sandbox Code Playgroud)

我想删除值为零的所有项目

所以它就像这样

{'1': 2, '3': 4, '2': 4, '5': 1, '4': 1}
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 6

使用字典理解:

In [94]: dic={'1': 2, '0': 0, '3': 4, '2': 4, '5': 1, '4': 1, '7': 0, '6': 0, '9': 0, '8': 0}

In [95]: {x:y for x,y in dic.items() if y!=0}
Out[95]: {'1': 2, '2': 4, '3': 4, '4': 1, '5': 1}
Run Code Online (Sandbox Code Playgroud)


Ble*_*der 6

使用字典理解:

{k: v for k, v in d.items() if v}
Run Code Online (Sandbox Code Playgroud)