Open In App

Python | Set 4 (Dictionary, Keywords in Python)

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
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



Similar Reads

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 explained above, this works together with "try" to catc
4 min read
Python program to extract Keywords from a list
Given a List of strings, extract all the words that are keywords. Input : test_list = ["Gfg is True", "Its a global win", "try Gfg"], Output : ['is', 'True', 'global', 'try'] Explanation : All strings in result list is valid Python keyword. Input : test_list = ["try Gfg"], Output : ['try'] Explanation : try is used in try/except block, hence a keyw
6 min read
Python Keywords and Identifiers
Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python programming language, there are a set of predefined words, called Keywords which along with Identifiers will form meaningful sentences when used together. Python keywords cannot be used as the names of variables, functions, and classes. In t
9 min read
Python Keywords
Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python programming language, there are a set of predefined words, called Keywords which along with Identifiers will form meaningful sentences when used together. Python keywords cannot be used as the names of variables, functions, and classes. In t
15 min read
Pafy - Getting Keywords for each item of Playlist
In this article we will see how we can get keywords of each item of playlist in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. A playlist in YouTube is a list, or group, of videos that plays in order, one video after the other. You
2 min read
Extract keywords from text with ChatGPT
In this article, we will learn how to extract keywords from text with ChatGPT using Python. ChatGPT is developed by OpenAI. It is an extensive language model based on the GPT-3.5 architecture. It is a type of AI chatbot that can take input from users and generate solutions similar to humans. ChatGPT is well trained AI that is trained on a large dat
4 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Practice Tags :