Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Dictionary keys() method
Next article icon

Python | Set 4 (Dictionary, Keywords in Python)

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python.

Dictionary in Python 

In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (Before python 3.7 dictionary used to be unordered meant key-value pairs are not stored in the order they are inputted into the dictionary but from python 3.7 they are stored in order like the first element will be stored in the first position and the last at the last position.)

Python3




# Create a new dictionary 
d = dict() # or d = {}
  
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345
  
# print the whole dictionary
print (d)
  
# print only the keys
print (d.keys())
  
# print only values
print (d.values())
  
# iterate over dictionary 
for i in d :
    print ("%s  %d" %(i, d[i]))
  
# another method of iteration
for index, key in enumerate(d):
    print (index, key, d[key])
  
# check if key exist
print ('xyz' in d)
  
# delete the key-value pair
del d['xyz']
  
# check again 
print ("xyz" in d)
 
 

Output: 

{'xyz': 123, 'abc': 345}  ['xyz', 'abc']  [123, 345]  xyz 123  abc 345  0 xyz 123  1 abc 345  True  False

Time Complexity: O(1)
Auxiliary Space: O(n)

break, continue, pass in Python 

  • break: takes you out of the current loop.
  • continue:  ends the current iteration in the loop and moves to the next iteration.
  • pass: The pass statement does nothing. It can be used when a statement is required. syntactically but the program requires no action.

It is commonly used for creating minimal classes.

Python3




# Function to illustrate break in loop
def breakTest(arr):
    for i in arr:
        if i == 5:
            break
        print (i)
    # For new line
    print("") 
  
# Function to illustrate continue in loop
def continueTest(arr):
    for i in arr:
        if i == 5:
            continue
        print (i)
  
    # For new line
    print("") 
  
# Function to illustrate pass 
def passTest(arr):
        pass
  
      
# Driver program to test above functions
  
# Array to be used for above functions:
arr = [1, 3 , 4, 5, 6 , 7]
  
# Illustrate break
print ("Break method output")
breakTest(arr)
  
# Illustrate continue 
print ("Continue method output")
continueTest(arr)
  
# Illustrate pass- Does nothing
passTest(arr)
 
 

Output: 

Break method output  1 3 4  Continue method output  1 3 4 6 7

Time complexity: O(n), where n is the length of the array arr.
Auxiliary space: O(1), since the space used is constant and does not depend on the size of the input.

map, filter, lambda

  • map: The map() function applies a function to every member of iterable and returns the result. If there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables.
  • filter:  It takes a function returning True or False and applies it to a sequence, returning a list of only those members of the sequence for which the function returned True.
  • lambda: Python provides the ability to create a simple (no statements allowed internally) anonymous inline function called lambda function. Using lambda and map you can have two for loops in one line.

Python3




# python program to test map, filter and lambda
items = [1, 2, 3, 4, 5]
  
#Using map function to map the lambda operation on items
cubes = list(map(lambda x: x**3, items))
print(cubes)
  
# first parentheses contains a lambda form, that is  
# a squaring function and second parentheses represents
# calling lambda
print( (lambda x: x**2)(5))
  
# Make function of two arguments that return their product
print ((lambda x, y: x*y)(3, 4))
  
#Using filter function to filter all 
# numbers less than 5 from a list
number_list = range(-10, 10)
less_than_five = list(filter(lambda x: x < 5, number_list))
print(less_than_five)
 
 

Output:

[1, 8, 27, 64, 125]  25  12  [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

For more clarity about map, filter, and lambda, you can have a look at the below example: 

Python3




# code without using map, filter and lambda
  
# Find the number which are odd in the list
# and multiply them by 5 and create a new list
  
# Declare a new list
x = [2, 3, 4, 5, 6]
  
# Empty list for answer
y = []
  
# Perform the operations and print the answer
for v in x:
    if v % 2:
        y += [v*5]
print(y)
 
 

Output: 

[15, 25]

The same operation can be performed in two lines using map, filter, and lambda as : 

Python3




# above code with map, filter and lambda
  
# Declare a list
x = [2, 3, 4, 5, 6]
  
# Perform the same operation as  in above post
y = list(map(lambda v: v * 5, filter(lambda u: u % 2, x)))
print(y)
 
 

Output:

[15, 25]

https://www.youtube.com/watch?v=z7z_e5-l2yE



Next Article
Python Dictionary keys() method

N

Nikhil Kumar Singh
Improve
Article Tags :
  • Python
  • School Programming
  • python-dict
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Sort Python Dictionary by Key or Value - Python
    There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary b
    6 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 min read
  • Python Dictionary keys() method
    keys() method in Python dictionary returns a view object that displays a list of all the keys in the dictionary. This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example: [GFGTABS] Python d = {'A': 'Geek
    2 min read
  • Dictionary with Tuple as Key in Python
    Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
    4 min read
  • Keywords in Python | Set 2
    Python Keywords - Introduction Keywords in Python | Set 1  More keywords:16. try : This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in "try" block is checked, if there is any type of error, except block is executed. 17. except : As expl
    4 min read
  • Python Dictionary items() method
    items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified. Example: [GFGTABS] Python d = {'A': 'Python', 'B': 'Java', 'C': 'C++'} #
    2 min read
  • Python Dictionary fromkeys() Method
    Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value. Python Dictionary fromkeys() Method Syntax: Syntax : fromkeys(seq, val) Parameters : seq : The sequence to be transformed into
    3 min read
  • Python Dictionary pop() Method
    The Python pop() method removes and returns the value of a specified key from a dictionary. If the key isn't found, you can provide a default value to return instead of raising an error. Example: [GFGTABS] Python d = {'a': 1, 'b': 2, 'c': 3} v = d.pop('b') print(v) v
    3 min read
  • Python Dictionary setdefault() Method
    Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. Python Dictionary setdefault() Method Syntax: Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key - Key to be sear
    2 min read
  • Iterate over a dictionary in Python
    In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences