Python, renowned for its simplicity and versatility, owes a significant part of its power to modules. Modules are an essential concept in Python programming, enabling developers to organize code, enhance reusability, and maintain a clean project structure. In this tutorial, we’ll delve into the world of Python modules, exploring their significance, creation, unique features, and diverse applications.
Importance of Modules
Modules serve as building blocks that encapsulate code, variables, and functions, making it easier to manage and scale projects. By grouping related functionalities together, modules facilitate code readability, reduce redundancy, and enable collaborative development. This modular approach enhances the maintainability and extensibility of Python applications.
Creating a Module
Creating a module is a straightforward process. To begin, save a collection of related functions and variables in a .py file. This file name becomes the module name. For instance, let’s create a simple module named math_operations:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
Features
Python modules offer a range of features that streamline development and optimize code organization:
Namespace Isolation: Modules create separate namespaces, preventing naming conflicts between variables and functions.
Reusability: Code encapsulated within modules can be easily reused in multiple projects.
Modularity: Modules support a modular architecture, enhancing code separation and maintainability.
Information Hiding: By controlling what is exposed in a module’s interface, you can encapsulate implementation details.
Standard Library: Python’s standard library provides a plethora of pre-built modules, saving time and effort in coding common functionalities.
Different Python Modules
Math Module: The math module offers a suite of mathematical functions. Let’s calculate the factorial of a number using the math module:
import math
num = 5
factorial = math.factorial(num)
print(f"The factorial of {num} is {factorial}")
Datetime Module: The datetime module simplifies date and time manipulation. Here’s an example of getting the current date and time:
import datetime
current_datetime = datetime.datetime.now()
print(f"Current date and time: {current_datetime}")
Random Module: The random module facilitates random number generation. Let’s generate a random integer between 1 and 100:
import random
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")
JSON Module: The json module simplifies JSON encoding and decoding. Here, we’ll encode a Python dictionary as a JSON string:
IntermediateLesson 31 of 4714 min read8 runnable examples
A class is a blueprint, and an object is a thing built from that blueprint. Classes bundle data (attributes) with the functions that work on it (methods). Page objects in test automation, models in web apps and most libraries you use are built from classes.
rex = Dog()
bella = Dog()
print(type(rex).__name__, rex is bella)
Output
Dog False
Each call to Dog() creates a new, separate object (an instance) of the class.
__init__ and self
__init__ runs automatically when an object is created. Use it to set the object’s starting attributes. self is the object being created; Python passes it for you.
self is just the conventional name for the first parameter. Every method needs it, because it is how the method reaches the object’s data.
Methods
Methods are functions defined inside a class. Call them on an object with a dot.
Python
classAccount:def__init__(self,owner,balance=0):self.owner=ownerself.balance=balancedefdeposit(self,amount):ifamount<=0:raiseValueError("Deposit must be positive")self.balance+=amountreturnself.balancedefwithdraw(self,amount):ifamount>self.balance:print("Insufficient funds")returnself.balanceself.balance-=amountreturnself.balanceacc=Account("Asha",100)print(acc.deposit(50))print(acc.withdraw(500))print(acc.withdraw(30))
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
acc.deposit(50) is really Account.deposit(acc, 50): the object goes into self.
Class attributes vs instance attributes
An attribute set on the class is shared by all objects. One set on self belongs to a single object.
Python
classEmployee:company="SQA Tools"# class attribute: sharedcount=0def__init__(self,name):self.name=name# instance attribute: per objectEmployee.count+=1a=Employee("Asha")b=Employee("Ravi")print(a.company,b.company,Employee.count)print(a.name,b.name)
def __init__(self, name):
self.name = name # instance attribute: per object
Employee.count += 1
a = Employee("Asha")
b = Employee("Ravi")
print(a.company, b.company, Employee.count)
print(a.name, b.name)
Output
SQA Tools SQA Tools 2
Asha Ravi
__str__ and __repr__
Special methods (with double underscores) let your objects work with built-in functions. __str__ controls print(); __repr__ controls how the object looks in lists and the shell.
IntermediateLesson 45 of 4714 min read11 runnable examples
NumPy is the foundation of numerical Python. Its ndarray stores numbers in a compact block of memory and runs maths on whole arrays at once, which is far faster and shorter than looping over lists. Pandas, scikit-learn and Matplotlib are all built on it.
Maths on an array applies to every element. The same operator on a list does something else:
Python
importnumpyasnpprices=[100,250,80]print(prices*2)# list: repeatedarr=np.array(prices)print(arr*2)# array: every element doubledprint(arr*1.18)# add 18% tax to allprint(arr+np.array([1,2,3]))# element-wise addition
importnumpyasnpg=np.arange(1,13).reshape(3,4)print(g[0,0],g[2,-1])print(g[1])# second rowprint(g[:,1])# second columnprint(g[0:2,1:3])# sub-grid
Output
1 12
[5 6 7 8]
[ 2 6 10]
[[2 3]
[6 7]]
Boolean masks
A comparison gives an array of True/False values, which you can use to select elements:
Python
importnumpyasnpscores=np.array([45,82,67,91,38,74])mask=scores>=60print(mask)print(scores[mask])print(scores[(scores>50)&(scores<80)])# use & and |, not and/orprint(np.where(scores>=60,"pass","fail"))
importnumpyasnpsales=np.array([[120,90,150],[80,110,95]])# 2 stores x 3 monthsprint(sales.sum(),sales.mean().round(2))print(sales.sum(axis=0))# per month (down the columns)print(sales.sum(axis=1))# per store (across the rows)print(sales.max(),sales.argmax(),np.median(sales))
Output
645 107.5
[200 200 245]
[360 285]
150 2 102.5
Tip
axis=0 means “collapse the rows” (one result per column) and axis=1 means “collapse the columns” (one result per row).
Broadcasting
When shapes differ, NumPy stretches the smaller array to fit, as long as the dimensions are compatible:
Python
importnumpyasnpmarks=np.array([[70,80,90],[60,75,85]])bonus=np.array([5,0,10])# one bonus per subjectprint(marks+bonus)print(marks/marks.max(axis=1,keepdims=True))# normalise each row
Fast numerical computing: arrays, linear algebra, statistics and random numbers. It is the base for pandas, SciPy, scikit-learn and most data and ML libraries.
What is the difference between a Python list and a NumPy array?
A NumPy array holds items of one type in contiguous memory and supports element-wise maths. A list can mix types and its operators mean concatenation and repetition.
What does axis=0 mean in NumPy?
It means “along the rows”, so the result has one value per column. axis=1 gives one value per row.
IntermediateLesson 46 of 4715 min read12 runnable examples
pandas turns tables of data into DataFrames that you can filter, sort, group and summarise in a few lines. It reads CSV, Excel, JSON and SQL, which makes it the everyday tool for data analysis and for preparing test data.
The examples were run with pandas 3. The in-browser Try it uses an older pandas, so a few outputs (such as column types) may print slightly differently there.
Series and DataFrame
A Series is one labelled column. A DataFrame is a table of Series that share an index.
importpandasaspddf=pd.DataFrame({"name":["Asha","Ravi","Meena"],"dept":["QA","Dev","QA"],"salary":[52000,61000,48000]})print(df["name"].tolist())# one columnprint(df[["name","salary"]])# several columnsprint(df.loc[1,"name"])# by labelprint(df.iloc[0].to_dict())# by position
Output
['Asha', 'Ravi', 'Meena']
name salary
0 Asha 52000
1 Ravi 61000
2 Meena 48000
Ravi
{'name': 'Asha', 'dept': 'QA', 'salary': 52000}
BeginnerLesson 41 of 4712 min read11 runnable examples
Programs save results, read test data and process logs, and all of that means working with files. Python’s built-in open() function plus a with block is all you need for text files.
In this lesson
Open files safely with with
Choose the right file mode
Read a whole file, a line, or all lines
Write, append and process files line by line
Write a file
open(path, mode) returns a file object. Mode "w" creates the file (or empties it if it exists). The with block closes the file automatically, even if an error happens.
Traceback (most recent call last):
File "main.py", line 1, in <module>
with open("does_not_exist.txt", encoding="utf-8") as f:
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'does_not_exist.txt'
Check first, or catch the error:
Python
frompathlibimportPathpath=Path("does_not_exist.txt")ifpath.exists():print(path.read_text(encoding="utf-8"))else:print(f"{path} not found, using defaults")try:open("does_not_exist.txt",encoding="utf-8")exceptFileNotFoundErrorase:print("Caught:",e.strerror)
Output
does_not_exist.txt not found, using defaults
Caught: No such file or directory
Process a log file
A typical job: read a log, count errors and write a summary.
Python
log="""2026-11-02 09:00 INFO start2026-11-02 09:01 ERROR db timeout2026-11-02 09:02 INFO retry2026-11-02 09:03 ERROR db timeout2026-11-02 09:04 WARN slow response"""withopen("app.log","w",encoding="utf-8")asf:f.write(log)counts={}errors=[]withopen("app.log",encoding="utf-8")asf:forlineinf:level=line.split()[2]counts[level]=counts.get(level,0)+1iflevel=="ERROR":errors.append(line.split(maxsplit=3)[3].strip())withopen("summary.txt","w",encoding="utf-8")asout:forlevel,ninsorted(counts.items()):out.write(f"{level}: {n}\n")print(open("summary.txt",encoding="utf-8").read().strip())print(set(errors))
Images, PDFs and zip files are binary. Open them with "rb" / "wb" and you get bytes:
Python
data=bytes([137,80,78,71])# the first bytes of every PNG filewithopen("sample.bin","wb")asf:f.write(data)withopen("sample.bin","rb")asf:head=f.read()print(head,len(head))
Output
b'\x89PNG' 4
seek and tell
Python
withopen("notes.txt",encoding="utf-8")asf:print(f.read(6))print(f.tell())# current positionf.seek(0)# back to the startprint(f.readline().strip())
Anonymous functions in Python, also known as lambda functions, allow you to create small, one-line functions without explicitly defining a function using the `def` keyword.
Syntax: `lambda arguments: expression`
The `lambda` keyword is used to define a lambda function. It is followed by the arguments (comma-separated) and a colon (:), then the expression that is evaluated and returned as the function’s result. Here is an example:
# Creating a lambda function to add two numbers
add_numbers = lambda x, y: x + y
# Calling the lambda function
result = add_numbers(10, 15)
print(result) # Output: 25
In this example, we define a lambda function `add_numbers` that takes two arguments, `x` and `y`. The function adds these two numbers together using the `+` operator and returns the result. We then call the lambda function by providing the arguments `10` and `15`, and store the returned value in the `result` variable.
Lambda functions are commonly used when you need a simple, one-line function and don’t want to define a separate named function. They are often used in combination with built-in functions like `map()`, `filter()`, and `reduce()` to perform operations on iterables in a concise and readable manner.
Features of Python Lambda Functions:
Anonymity: Lambda functions do not have a name, making them useful for short, simple operations where defining a separate function using def is not necessary.
Compactness: Lambda functions are typically concise and can be defined in a single line.
SingleExpression: Lambda functions are limited to a single expression, which means they cannot contain multiple statements or complex logic.
FunctionalProgramming: Lambda functions are commonly used in functional programming to pass behavior as arguments to higher-order functions like map, filter, and reduce.
Difference between Built-in functions and Lambda functions (also known as Anonymous functions)
In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.
Built-in Functions:
Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:
# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length) # Output: 5
In this example, the len() function is a built-in function that returns the number of elements in the list numbers.
Lambda Functions (Anonymous Functions):
Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce().
Lambda functions have the following structure: lambda arguments: expression
The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:
# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result) # Output: 25
In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.
Key Differences:
Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.
Python is a powerful and versatile programming language that comes with a rich set of built-in functions. These functions are pre-defined and readily available, making it easier for developers to accomplish various tasks without having to write the code from scratch. In this tutorial, we will explore what built-in functions are in Python, provide examples of some commonly used built-in functions, and explain the difference between built-in functions and user-defined functions.
What are Built-in Functions in Python?
Built-in functions are functions that are built into the Python programming language. They are always available and do not require any additional installations or imports. These functions are designed to perform common tasks and operations on different types of data. Python provides a wide range of built-in functions, which can be broadly categorized into the following types:
Mathematical Functions: These functions perform various mathematical operations such as calculating absolute values, rounding numbers, finding maximum and minimum values, and more.
String Functions: String functions handle operations on strings, such as concatenation, case conversions, finding substrings, and more.
List Functions: List functions deal with operations on lists, including sorting, adding elements, removing elements, and more.
Dictionary Functions: These functions work with dictionaries, enabling operations like accessing keys, values, merging dictionaries, etc.
File Input/Output Functions: File-related functions help in reading from and writing to files.
Type Conversion Functions: Type conversion functions allow you to convert data from one type to another, such as converting integers to strings or vice versa.
Other Utility Functions: Python also provides several other utility functions for tasks like input/output, formatting, etc.
Now, let’s explore some examples of commonly used built-in functions in Python.
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is an example file.")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: "Hello, this is an example file."
Difference Between Built-in Functions and User-defined Functions:
The primary difference between built-in functions and user-defined functions lies in their origin and availability. Built-in functions are provided by the Python language itself and are readily available for use without any additional code. On the other hand, user-defined functions are created by the developers themselves to perform specific tasks and are not available in the language by default. Here’s an example to illustrate the difference:
User-defined Function:
def square(x):
return x ** 2
result = square(5)
print(result) # Output: 25
In the user-defined function example, we define a function called “square” that takes a parameter “x” and returns its square. In the built-in function example, we use the “sum” function, which is already provided by Python, to calculate the sum of the elements in the list.
Difference between Built-in functions and anonymous functions (also known as lambda functions)
In Python, the main difference between built-in functions and anonymous functions (also known as lambda functions) lies in their structure, creation, and usage.
Built-in Functions:
Built-in functions in Python are pre-defined functions that are provided by the Python language itself. They are readily available for use without any additional coding or import statements. These functions cover a wide range of tasks and operations, such as mathematical calculations, string manipulations, list operations, file I/O, etc. They are named and can be used repeatedly throughout the code. Here’s an example of using a built-in function to find the length of a list:
# Using the built-in function len() to find the length of a list
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print(length) # Output: 5
In this example, the len() function is a built-in function that returns the number of elements in the list numbers.
Anonymous Functions (Lambda Functions):
Lambda functions are a special type of function in Python that allows you to create small, one-line functions without explicitly defining them using the def keyword. Lambda functions are typically used for simple, one-time tasks and are often used in conjunction with higher-order functions like map(), filter(), and reduce(). Lambda functions have the following structure: lambda arguments: expression
The lambda function takes a set of arguments, performs the specified expression on those arguments, and returns the result of the expression. Here’s an example of a lambda function that calculates the square of a number:
# Using a lambda function to calculate the square of a number
square = lambda x: x**2
result = square(5)
print(result) # Output: 25
In this example, we create a lambda function that takes an argument x, calculates the square using the expression x**2, and then we call the lambda function with square(5) to calculate the square of 5.
Key Differences:
Structure and Definition: Built-in functions are predefined and come with Python, whereas lambda functions are created on-the-fly and are not explicitly defined using the def keyword.
Usage and Complexity: Built-in functions are used for a wide range of tasks and can be complex with multiple parameters, whereas lambda functions are typically used for simple operations with one or few parameters.
Naming: Built-in functions have names, and you can call them using their names whenever needed. Lambda functions, on the other hand, do not have names and are often used as temporary, inline functions.
Return Statement: Built-in functions return their results as any other function, using the return statement. Lambda functions automatically return the value of the expression without using the return statement.
Use Cases: Built-in functions are ideal for general-purpose and reusable tasks, while lambda functions are more suited for immediate, short-term, and one-time uses.
BeginnerLesson 21 of 477 min read6 runnable examples
Lists and tuples both store ordered sequences, and both support indexing, slicing and loops. The difference that matters is that a list can change and a tuple cannot. That one difference decides which to use.
Traceback (most recent call last):
File "main.py", line 1, in <module>
visited = {[0, 0], [0, 1]}
^^^^^^^^^^^^^^^^
TypeError: cannot use 'list' as a set element (unhashable type: 'list')
Use a list when the collection will change: items are added, removed or sorted, such as a shopping cart or a queue of test cases.
Use a tuple when the values belong together and should not change, such as (latitude, longitude), an RGB colour, a function returning several values, or a dictionary key.
Check your understanding
Quick quiz
1. Which can be used as a dictionary key?
Lists are mutable and therefore unhashable.
2. Which uses less memory for the same five numbers?
A list keeps extra capacity so it can grow.
3. You need to store an employee’s (id, name, joining date) record that never changes. Which fits best?
It is a fixed record, so a tuple communicates intent and protects it from accidental changes.
Program Practice
70 Python Tuple Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Creating and iterating over a tuple is slightly faster and it uses less memory. The difference rarely matters; choose based on whether the data should change.
Why use a tuple instead of a list?
To signal that the data is fixed, to protect it from accidental changes, to use it as a dictionary key or set member, and to save a little memory.
Can a tuple contain a list?
Yes. The tuple cannot be changed, but the list inside it can. Such a tuple is not hashable, so it cannot be a dict key.
BeginnerLesson 24 of 4714 min read11 runnable examples
A function is a named block of code that you can run whenever you need it. Functions remove repetition, give a name to an idea, and make code easy to test. Every practice program becomes cleaner once it is wrapped in a function.
In this lesson
Define and call functions
Pass positional, keyword and default arguments
Return one or several values
Accept any number of arguments with *args and **kwargs
Define and call a function
def starts a function, followed by its name, brackets and a colon. The indented block is the body. Nothing runs until you call the function.
Python
defgreet():print("Hello from a function")greet()greet()
Output
Hello from a function
Hello from a function
Parameters and arguments
Parameters are the names in the definition; arguments are the values you pass in the call.
Python
defgreet(name,course):print(f"Hi {name}, welcome to {course}")greet("Asha","Python")greet(course="Playwright",name="Ravi")# keyword arguments: any order
Output
Hi Asha, welcome to Python
Hi Ravi, welcome to Playwright
Return a value
return sends a value back to the caller and ends the function. A function without return gives back None.
Never use a mutable value such as [] as a default. It is created once, when the function is defined, and shared by every call:
Python
defadd_item(item,basket=[]):# bugbasket.append(item)returnbasketprint(add_item("pen"))print(add_item("book"))# the old pen is still theredefadd_item_fixed(item,basket=None):# fixifbasketisNone:basket=[]basket.append(item)returnbasketprint(add_item_fixed("pen"),add_item_fixed("book"))
Output
['pen']
['pen', 'book']
['pen'] ['book']
*args: any number of positional arguments
A parameter with one * collects extra positional arguments into a tuple.
and * also work the other way: they spread a list or dict into separate arguments.
Python
defdescribe(name,role,city):returnf"{name} ({role}) from {city}"row=["Meena","tester","Pune"]info={"name":"Ravi","role":"dev","city":"Delhi"}print(describe(*row))print(describe(**info))
Output
Meena (tester) from Pune
Ravi (dev) from Delhi
Docstrings and type hints
Python
defdiscount(price:float,percent:float=10)->float:"""Return the price after taking off `percent` per cent."""returnround(price*(1-percent/100),2)print(discount(499.0))print(discount.__doc__)
Output
449.1
Return the price after taking off `percent` per cent.
Type hints (price: float, -> float) document what the function expects. Python does not enforce them, but IDEs and tools such as mypy use them to catch mistakes.
Functions are objects
A function can be stored in a variable, put in a list, or passed to another function:
a and b take the first two values, *rest collects any extra positional values into a tuple, and **opts collects keyword arguments into a dict.
Quick quiz
1. What does a function return if it has no return statement?
Every function returns something; without return it is None.
2. Which definition is valid?
Parameters with defaults must come after those without.
3. Inside def f(*args), what type is args?
*args collects positional arguments into a tuple; **kwargs gives a dict.
4. Why is def f(items=[]) a problem?
The default is created once, so changes persist across calls. Use None instead.
Exercise: is it a palindrome?
Write is_palindrome(text) that ignores case and spaces, and returns True or False.
Input
"Never odd or even", "Python"
Expected output
Never odd or even -> True
Python -> False
Hint 1
Clean the text first: "".join(text.lower().split()).
Hint 2
Compare the cleaned text with its reverse [::-1].
Python
defis_palindrome(text):cleaned="".join(text.lower().split())returncleaned==cleaned[::-1]fortin["Never odd or even","Python"]:print(t,"->",is_palindrome(t))
Output
Never odd or even -> True
Python -> False
split() with no arguments removes all spaces and join glues the words back together. The function returns the comparison result directly, so callers can use it in if statements.
Program Practice
39 Python Function Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
What is the difference between a parameter and an argument?
A parameter is the name in the function definition (def greet(name)). An argument is the value passed in a call (greet("Asha")).
What are *args and **kwargs in Python?
args collects extra positional arguments into a tuple; kwargs collects extra keyword arguments into a dict. The names are conventions; the and do the work.
Can a Python function return multiple values?
Yes. return a, b returns a tuple, which the caller can unpack: x, y = f().
What is the difference between print and return in a function?
print shows text on the screen. return hands a value back to the caller so it can be used in further code.
BeginnerLesson 23 of 4713 min read10 runnable examples
A dictionary stores data as key-value pairs, so you can look a value up by a meaningful key instead of a position. Dictionaries model JSON, configuration, database rows and counters, which makes them one of the most used types in Python.
In this lesson
Create dictionaries and read values safely
Add, update and delete keys
Loop over keys, values and items
Work with nested dicts and merging
Create a dictionary
Write key: value pairs inside curly braces. Keys are usually strings, but any immutable value works.
Python
user={"name":"Asha","role":"tester","years":4}print(user)print(len(user))ports=dict(http=80,https=443)# dict() with keyword argumentsprint(ports)
Since Python 3.7, dictionaries keep the order in which keys were inserted.
Read values
Use square brackets with the key. A missing key raises KeyError, so use get() when a key may be absent.
Python
user={"name":"Asha","role":"tester"}print(user["name"])print(user.get("email"))# None instead of an errorprint(user.get("email","not provided"))# with a defaultprint("role"inuser)# checks keys
Output
Asha
None
not provided
True
Python
user={"name":"Asha"}print(user["email"])
Output
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(user["email"])
~~~~^^^^^^^^^
KeyError: 'email'
Add, change and delete
Python
config={"browser":"chromium","headless":True}config["timeout"]=30# add a new keyconfig["browser"]="firefox"# replace an existing valueconfig.update({"retries":2,"headless":False})print(config)removed=config.pop("retries")# remove and returndelconfig["timeout"]# removeprint(removed,config)
stock={"pen":40,"notebook":0,"bag":7}foriteminstock:# keysprint(item,end=" ")print()print(list(stock.values()))foritem,qtyinstock.items():# key and value togetherifqty==0:print(item,"is out of stock")
Output
pen notebook bag
[40, 0, 7]
notebook is out of stock
Count things with a dict
Counting is the classic dictionary job:
Python
text="the quick brown fox jumps over the lazy dog the end"counts={}forwordintext.split():counts[word]=counts.get(word,0)+1print(counts["the"])top=max(counts,key=counts.get)print(top,counts[top])
Output
3
the 3
Tip
collections.Counter does this in one line: Counter(text.split()).most_common(1). See the Collections lesson.
Nested dictionaries
Values can be lists or other dictionaries, which is exactly the shape of JSON data.