The Wayback Machine - https://web.archive.org/web/20240927193702/https://www.geeksforgeeks.org/python-set-4-dictionary-keywords-python/
Open In App

Python | Set 4 (Dictionary, Keywords in Python)

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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
10 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 | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python dictionary, set and counter to check if frequencies can become same
Given a string which contains lower alphabetic characters, we need to remove at most one character from this string in such a way that frequency of each distinct character becomes same in the string. Examples: Input : str = “xyyz” Output : Yes We can remove character ’y’ from above string to make the frequency of each character same. Input : str =
2 min read
Python | Words extraction from set of characters using dictionary
Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It checks if a string is a word or not and returns true
3 min read
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python provides us with several in-built data structures such as lists, tuples, sets, and dictionaries that store and organize the data efficiently. In this article, we will learn the difference between them and their applications in Python. Table of Content Difference between List, Tuple, Set, and DictionaryPython ListApplications of Python ListPy
11 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Dictionary and counter in Python to find winner of election
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to the candidate. Print the name of candidates received Max vote. If there is tie, print a lexicographically smaller name. Examples: Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny",
3 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python Dictionary to find mirror characters in a string
Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We hav
2 min read
Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe have existing solution for this problem please refer
3 min read
Python Dictionary clear()
The clear() method removes all items from the dictionary. Syntax: dict.clear() Parameters: The clear() method doesn't take any parameters. Returns: The clear() method doesn't return any value. Parameters: The clear() method take O(n) time. Examples: Input : d = {1: "geeks", 2: "for"} d.clear() Output : d = {} Error: As we are not passing any parame
2 min read
Python Dictionary copy()
Python Dictionary copy() method returns a shallow copy of the dictionary. let's see the Python Dictionary copy() method with examples: Examples Input: original = {1:'geeks', 2:'for'} new = original.copy() // Operation Output: original: {1: 'one', 2: 'two'} new: {1: 'one', 2: 'two'}Syntax of copy() method Syntax: dict.copy() Return: This method does
3 min read
Python dictionary values()
values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get "dict_values object". It must be cast to obtain the actual list. Python Dictionary values() Method Syntax Syntax: dictionary_name.values(
2 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
3 min read
Counting the frequencies in a list using dictionary in Python
Given an unsorted list of some elements(which may or may not be integers), Find the frequency of each distinct element in the list using a Python dictionary. Example: Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] Output: 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2 Explanation: Here 1 occurs 5 times, 2 occurs 4 times and so on... The problem can be s
4 min read
Python | Passing dictionary as keyword arguments
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it's values as argument values. Let's d
3 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Python | Ways to Copy Dictionary
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. When we simply assign dict1 = dict2 it refers to the same dictionary. Let's discuss a few ways to copy the
3 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 a dictionary.val : Initial values that need to be
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 searched in the dictionary. default_value (optional) -
2 min read
Python Dictionary popitem() method
Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple. Python Dictionary popitem() Method Syntax: Syntax : dict.popitem() Parameters : None Returns : A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary. Note: popitem() method return
2 min read
Python | Dictionary has_key()
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key: value pair. Note: has_key() method was removed in Python 3. Use the in operator instead. In Python Dictionary, has_key() method returns true if specifi
2 min read
Practice Tags :