• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

How to Remove All Zero/None/Null from Dictionary in Python?

Aniruddha Chaudhari/26721/2
CodePython

Dictionary is a prominent data structure in Python to store the key and value pair data. Every key in the dictionary has its associated value. That value can be anything legit data structure in python.

Sometimes we need to remove all the dictionary key-value pair having value equals to zero.

Program to remove all 0 from dictionary in Python

Method 1: Using for Loop

We can loop over the dictionary value and can put the check if the value is not equal to zero. In an earlier complete Python dictionary tutorial, we have seen how you can iterate over a complete Python dictionary.

dic_in = {'a': 2, 'b': 0, 'c': 4, 'd': 4, 'e': 0}
dic_out = {}
for x, y in dic_in.items():
    if y != 0:
        dic_out[x] = y

print(dic_out)

Output:

{'a': 2, 'c': 4, 'd': 4}

We are doing lot of labor work here. Can we optimize this code using some Python advance concepts?

Yes. We can do it.

Method 2: Using Python Compression Technique

There is also the easiest way to do this using the python compression technique.

Here is simple code spinet we can use it to filter out the the dictionary items having values zero.

{x:y for x,y in dic.items() if y!=0}

You can run the complete program here that removes all 0 from the dictionary in Python.

dic_in = {'a': 2, 'b': 0, 'c': 4, 'd': 4, 'e': 0}
dic_out = {x:y for x,y in dic_in.items() if y!=0}
print(dic_out)

Output:

{'a': 2, 'c': 4, 'd': 4}

This comprehension runs a loop over the key-value pair of a dictionary item. There is ‘if’ condition that excludes all the dictionary items having value equals to zero.

Similarly, you can write a program to remove all the dictionary elements have negative value by tweaking condition in the code.

Related Program: How to Set Default Dictionary Python Value?

Removing None Type Values from Dictionary

Many times, before processing a dictionary, project demands to remove all the dictionary entries having value None or Null.

If you don’t know Python has a None data type which is equivalent to Null data type from many of the other programming languages.

Here is the simple program that removes all the dictionary items having value None.

dic_in = {'a': 2, 'b': 0, 'c': None, 'd': 4, 'e': None}
dic_out = {x:y for x,y in dic_in.items() if y is not None}
print(dic_out)

Output:

{'a': 2, 'b': 0, 'd': 4}

Removing Zero and None Type Values from Dictionary

You can also combine the above two cases to remove all the entries having values zero or None type.

dic_in = {'a': 2, 'b': 0, 'c': 0, 'd': 4, 'e': None}
dic_out = {x:y for x,y in dic_in.items() if (y is not None and y!=0) }
print(dic_out)

Output:

{'a': 2, 'd': 4}

Here we are using logical ‘and’ operation.

Use Case

One of the best use cases, filtering all the students who scored marks more than 50.

Suppose you have a dictionary that maintains the student’s exam score data where the key is student’s id and value is student’s mark.

Note: Comprehension is a generic technique where you can put any if condition as per the requirement. It filters the dictionary item as per the condition.

It’s so easy. Right?

Python is known for its simplicity.

Python Interview Questions eBook

PythonPython Dictionary
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Ignacio Olaeta
    July 10, 2020 at 11:10 am
    dicSample = {'a': 2, 'b': 0, 'c': 4, 'd': 4, 'e': 0}
    dicSample2 = {x:y for x,y in dicSample.items() if y!=0}
    print (dicSample2)
    

    or

    dic = {'a': 2, 'b': 0, 'c': 4, 'd': 4, 'e': 0}
    dicSample2 = {x:y for x,y in dic.items() if y!=0}
    print (dicSample2)
    
    • Reply
      Aniruddha Chaudhari
      July 11, 2020 at 10:37 am

      There was a typo mistake. Thanks for the correction, Ignacio.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard