KEMBAR78
13 BSC CS Python CHP 4 | PDF | String (Computer Science) | Computing
0% found this document useful (0 votes)
9 views12 pages

13 BSC CS Python CHP 4

This document provides an overview of strings and lists in Python, detailing their creation, manipulation, and common functions. It explains string immutability, various string methods, and how to work with lists, including operations like appending, removing, and sorting elements. The document includes numerous examples to illustrate the concepts discussed.

Uploaded by

HARSH MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

13 BSC CS Python CHP 4

This document provides an overview of strings and lists in Python, detailing their creation, manipulation, and common functions. It explains string immutability, various string methods, and how to work with lists, including operations like appending, removing, and sorting elements. The document includes numerous examples to illustrate the concepts discussed.

Uploaded by

HARSH MISHRA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

13 B.Sc. CS Sem - I ​ 4.

Strings, Lists, Tuples and Dictionaries

text = "This is line 1.\nThis is


Strings in Python
line 2."​
A string in Python is a sequence of characters print(text)
enclosed within either single ('...') or
double ("...") quotes. Example 4: Concatenating Strings

Strings are immutable, meaning that once


str1 = "Hello"​
created, they cannot be modified.
str2 = "World"​
Creating Strings result = str1 + ", " + str2 +
"!"​

E
You can create a string by assigning a print(result) # Output: Hello,
sequence of characters to a variable using

EG
World!
either single or double quotes.

Multi-line strings can be created using triple Example 5: Repeating Strings You can also

LL
quotes. repeat a string multiple times using the *
operator.

O
Syntax:

C
repeat_str = "Hello " * 3​
# Using single quotes​ print(repeat_str) # Output:
str1 = 'Hello, World!'​
EE
Hello Hello Hello

# Using double quotes​
Functions of Strings in Python
R

str2 = "Python Programming"​



EG

Python provides a variety of built-in functions


# Using triple quotes for and methods to work with strings.
multi-line strings​
.D

str3 = """This is a ​ These functions allow for manipulating


multi-line string.""" strings, checking content, and performing
transformations like converting cases,
.M

searching, splitting, and joining.


Examples
.P

String methods help simplify tasks, such as


Example 1: Simple String Creation formatting output, preparing text for further
IG

processing, or applying transformations.


greeting = 'Hello'​
Commonly Used String Functions
print(greeting) # Output: Hello
R

len() - Returns the length of the string.​


SH

Example 2: Multi-line String


text = "Hello"​
message = """Welcome to Python print(len(text)) # Output: 5
Programming.​ str.lower() - Converts all characters in
It's a powerful language for the string to lowercase.​
beginners and experts alike."""​
print(message) text = "Python Programming"​
print(text.lower()) # Output:
Example 3: Using Escape Characters You can python programming
use escape characters to include special
characters like newline (\n) or tab (\t) within
a string.
1
str.upper() - Converts all characters in str.join(iterable) - Joins elements of
the string to uppercase.​ an iterable (e.g., list) into a single string,
separated by the string.​
text = "Python Programming"​
print(text.upper()) # Output: words = ["Python", "is", "fun"]​
PYTHON PROGRAMMING print(" ".join(words)) #
Output: Python is fun
str.capitalize() - Capitalizes the first
character of the string.

Examples
text = "hello world"​
print(text.capitalize()) # Example 1: Using len(), upper(), and

E
Output: Hello world lower()

EG
str.title() - Capitalizes the first
character of each word.​ message = "Hello, World!"​
print(len(message)) #

LL
Output: 13​
text = "hello world"​
print(message.upper()) #
print(text.title()) # Output:

O
Output: HELLO, WORLD!​
Hello World
print(message.lower()) #

C
str.strip() - Removes any leading and Output: hello, world!
trailing whitespace from the string.​
EE
Example 2: Stripping Whitespace and
text = " Hello, World! "​ Replacing Substrings
R

print(text.strip()) # Output:
EG

"Hello, World!" text = " Welcome to Python


str.replace(old, new) - Replaces all Programming "​
occurrences of a substring with another cleaned_text = text.strip()​
.D

substring.​ print(cleaned_text) #
Output: Welcome to Python
.M

text = "I love programming"​ Programming​


print(text.replace("love", print(cleaned_text.replace("Pyth
.P

"enjoy")) # Output: I enjoy on", "Java")) # Output: Welcome


programming to Java Programming
IG

str.find(substring) - Returns the


lowest index of the substring if it’s found in
Example 3: Finding and Splitting
R

the string; returns -1 otherwise.​


SH

quote = "The quick brown fox


text = "Hello, World!"​ jumps over the lazy dog"​
print(text.find("World")) # print(quote.find("fox")) #
Output: 7 Output: 16​
str.split(delimiter) - Splits the words = quote.split()​
string into a list, based on the delimiter.​ print(words) #
​ Output: ['The', 'quick',
'brown', 'fox', 'jumps', 'over',
text = "Python is fun"​ 'the', 'lazy', 'dog']
print(text.split()) # Output:
['Python', 'is', 'fun'] Example 4: Joining List Elements

2
words = ["Data", "Science", name = "Alice"​
"is", "amazing"]​ age = 25​
sentence = " ".join(words)​ print(f"My name is {name} and I
print(sentence) # am {age} years old.")
Output: Data Science is amazing
Checking String Content
Example 5: Using title() and
capitalize() ○​str.isdigit() checks if all characters
are digits.
○​str.isalpha() checks if all characters
text = "hello world"​ are alphabetic.
print(text.title()) # ○​str.isalnum() checks if characters are

E
Output: Hello World​ alphanumeric.

EG
print(text.capitalize()) #
Output: Hello world text = "Python3"​
print(text.isalpha()) # Output:

LL
Working with Strings in Python False​
print(text.isalnum()) # Output:
Manipulating Strings

O
True

C
Python strings come with many methods to
perform various operations, such as searching, Searching for Substrings
replacing, and modifying text.
EE
○​str.find() returns the index of the
By working with strings, you can handle user first occurrence of the substring (or -1 if
R

inputs, format text, and manage data not found).


effectively. ○​str.count() counts occurrences of a
EG

substring.
Common String Manipulation Techniques ○​str.startswith() /
str.endswith() checks if the string
.D

Concatenation​
starts/ends with a specific substring.
Combines multiple strings into a single string
using the + operator.​
.M

message = "Hello, World!"​


print(message.find("World"))
.P

first = "Hello"​
# Output: 7​
second = "World"​
print(message.count("o"))
IG

result = first + " " + second​


# Output: 2​
print(result) # Output: Hello
print(message.startswith("He"))
World
R

# Output: True
Repetition​
SH

Modifying Case​
Repeats a string multiple times using the *
Methods like str.upper(),
operator.​
str.lower(), str.capitalize(), and
str.title() change the case of characters.​
word = "Hi! "​
print(word * 3) # Output: Hi!
sentence = "learning python"​
Hi! Hi!
print(sentence.capitalize()) #
String Formatting​ Output: Learning python
Uses placeholders to format and insert
variables into a string, which can be done with
f-strings, format(), or %.​ Splitting and Joining Strings

3
○​str.split(delimiter) splits a # Output: 12​
string into a list based on the given print(sentence.count("in"))
delimiter.
# Output: 3
○​str.join(iterable) joins a list
into a string with elements separated by a
specified delimiter. Example 5: Splitting and Joining

words = "Python is easy to text = "apples, oranges,


learn"​ bananas"​
word_list = words.split() # fruit_list = text.split(", ")​
Output: ['Python', 'is', 'easy', print(fruit_list)
'to', 'learn']​ # Output: ['apples', 'oranges',

E
print(" | ".join(word_list)) # 'bananas']​
Output: Python | is | easy | to new_text = " and

EG
| learn ".join(fruit_list)​
print(new_text)

LL
Examples of Working with Strings # Output: apples and oranges and
bananas
Example 1: Concatenation and Repetition

O
Finding the Number of Characters and

C
greeting = "Good " + "Morning"​ Words in a String
repeat_greeting = greeting * 2​ Counting Characters Use the len()
EE
print(greeting) # function to find the number of characters in a
Output: Good Morning​ string, including spaces.​
R

print(repeat_greeting) #
Output: Good MorningGood Morning text = "Python programming"​
EG

print(len(text)) # Output: 18
(counts spaces as well)
Example 2: Formatting with f-strings
.D

Counting Words You can split the string into


name = "John"​ a list of words using split(), then use
.M

score = 95​ len() on the list to count words.​


print(f"{name} scored {score}%
.P

on the test.") # Output: John


text = "Python programming is
IG

scored 95% on the test.


fun"​
word_count = len(text.split())​
Example 3: Checking for Digits and
R

print(word_count) # Output: 4
Alphabets
SH

data = "12345"​ Inserting Substrings into a String


print(data.isdigit()) # Syntax:
Output: True​
print(data.isalpha()) # # Insert substring at index
Output: False position​
new_string =
Example 4: Finding and Counting Substrings original_string[:index] +
substring +
sentence = "The rain in Spain original_string[index:]
falls mainly in the plain."​
print(sentence.find("Spain")) Examples
4
Example 1: Counting Characters exciting

sentence = "Count the


characters!"​ Lists in Python
char_count = len(sentence)​ A list in Python is a collection that is ordered,
print(f"Number of characters: mutable, and allows duplicate elements.
{char_count}") # Output: Number
of characters: 21 Lists can store different data types, including
numbers, strings, and even other lists.

Example 2: Counting Words Lists are defined by enclosing items in square


brackets [] and separating them with
sentence = "Count the words in commas.

E
this sentence."​

EG
word_count = Syntax and Example:
len(sentence.split())​ # Creating a list​
print(f"Number of words: fruits = ["apple", "banana",

LL
{word_count}") # Output: Number "cherry"]​
of words: 6 numbers = [1, 2, 3, 4, 5]​

O
mixed_list = ["text", 10, 5.5,

C
Example 3: Inserting a Substring at a Specific True]​
Index ​
EE
print(fruits) # Output:
text = "Hello World"​ ['apple', 'banana', 'cherry']​
# Inserting " Python" at index 5​ print(numbers) # Output: [1,
R

new_text = text[:5] + " Python" 2, 3, 4, 5]​


EG

+ text[5:]​ print(mixed_list) # Output:


print(new_text) # Output: Hello ['text', 10, 5.5, True]
Python World
.D

List Functions and Methods


Example 4: Inserting at the Beginning of the
.M

String Python provides several built-in functions and


methods for working with lists, allowing you
.P

to manipulate, sort, and modify elements in


text = "Programming is great"​ various ways.
prefix = "Python "​
IG

new_text = prefix + text​ Common Functions and Methods:


print(new_text) # Output:
R

Python Programming is great len() - Returns the number of elements in the


list.
SH

fruits = ["apple", "banana",


Example 5: Inserting a Word in the Middle of
a Sentence "cherry"]​
print(len(fruits)) # Output: 3
text = "Data Science is append() - Adds an element at the end of the
exciting"​ list.​
insert_word = "and challenging "​
# Insert after "Data Science "​ fruits.append("orange")​
new_text = text[:13] + print(fruits) # Output:
insert_word + text[13:]​ ['apple', 'banana', 'cherry',
print(new_text) # Output: Data 'orange']
Science and challenging is

5
insert() - Inserts an element at a specified ['apple', 'banana', 'cherry']
index.​

List Operations
fruits.insert(1, "kiwi")​
Concatenation (+) - Combines two lists.​
print(fruits) # Output:
['apple', 'kiwi', 'banana',
'cherry'] list1 = [1, 2, 3]​
list2 = [4, 5, 6]​
remove() - Removes the first occurrence of the combined = list1 + list2​
specified element.​
print(combined) # Output: [1,
2, 3, 4, 5, 6]
fruits.remove("banana")​
Repetition (*) - Repeats the list a specified

E
print(fruits) # Output:
number of times.​
['apple', 'cherry']

EG
pop() - Removes and returns the element at the repeated = list1 * 3​
specified index (default is the last item).​
print(repeated) # Output: [1,

LL
2, 3, 1, 2, 3, 1, 2, 3]
fruits.pop(2)​
Membership (in) - Checks if an element

O
print(fruits) # Output:
exists in the list.​
['apple', 'banana']

C
index() - Returns the index of the first print(3 in list1) # Output:
EE
occurrence of the specified element.​
True​
print(10 in list1) # Output:
print(fruits.index("cherry")) #
R

False
Output: 2
EG

Iteration - Loops through each item in the list.​


count() - Returns the number of occurrences ​
of a specified element.​
.D

for fruit in fruits:​


print(fruits.count("apple")) # print(fruit)​
Output: 1
.M

# Output:​
sort() - Sorts the list in ascending order.​ # apple​
.P

# banana​
numbers = [4, 2, 9, 1]​ # cherry
IG

numbers.sort()​
print(numbers) # Output: [1, 2, Examples of List Operations
R

4, 9]
Example 1: Adding and Removing Elements
SH

reverse() - Reverses the order of elements in


the list.​
colors = ["red", "green",
"blue"]​
fruits.reverse()​ colors.append("yellow")​
print(fruits) # Output: colors.remove("green")​
['cherry', 'banana', 'apple'] print(colors) # Output: ['red',
copy() - Returns a copy of the list.​ 'blue', 'yellow']

fruits_copy = fruits.copy()​ Example 2: Inserting Elements


print(fruits_copy) # Output:

6
colors.insert(1, "purple")​ ●​ step - The interval between elements
(optional).
print(colors) # Output: ['red',
'purple', 'blue', 'yellow'] Example:

Example 3: Sorting and Reversing numbers = [0, 1, 2, 3, 4, 5, 6]​


print(numbers[1:5]) #
numbers = [7, 1, 4, 2]​ Output: [1, 2, 3, 4]​
numbers.sort()​ print(numbers[:4]) #
print(numbers) # Output: [1, 2, Output: [0, 1, 2, 3]​
4, 7]​ print(numbers[::2]) #
numbers.reverse()​ Output: [0, 2, 4, 6]​

E
print(numbers) # Output: [7, 4, print(numbers[::-1]) #
2, 1] Output: [6, 5, 4, 3, 2, 1, 0]

EG
Nested Lists

LL
Example 4: Copying and Counting Elements
A nested list is a list that contains other lists as
new_colors = colors.copy()​ its elements.

O
print(new_colors.count("red")) Example:

C
# Output: 1
EE
matrix = [​
Example 5: List Concatenation and Repetition [1, 2, 3],​
[4, 5, 6],​
R

even = [2, 4, 6]​ [7, 8, 9]​


EG

odd = [1, 3, 5]​ ]​


combined = even + odd​ ​
print(combined) # Output: [2, # Accessing elements in a nested
.D

4, 6, 1, 3, 5]​ list​
print(odd * 2) # Output: [1, print(matrix[1][2]) # Output: 6
.M

3, 5, 1, 3, 5] (second row, third column)


.P

List Slices Tuples


IG

List slicing allows you to access a specific A tuple is an immutable, ordered collection in
portion (or "slice") of a list by specifying a Python, which means elements cannot be
range of indices. added, removed, or changed after creation.
R

This feature helps extract sublists, create Tuples are typically used for data that should
SH

copies, and perform various operations on not be modified, like constant values or fixed
portions of lists without affecting the original data records.
list.
Syntax:
Syntax:
# Creating a tuple​
list[start:end:step] coordinates = (10, 20)

●​ start - The index at which the slice


Tuples can be created using parentheses (), or
begins (inclusive).
without any brackets, separated by commas.
●​ end - The index at which the slice
ends (exclusive). Example:

7
colors = ("red", "green", [7, 8, 9]​
"blue")​ ]​
numbers = 1, 2, 3​ print(matrix[2][1]) # Output: 8
print(colors) # Output:
('red', 'green', 'blue')​ Example 3: Creating and Using Tuples
print(numbers) # Output: (1,
2, 3) # Defining a tuple and using it​
dimensions = (10, 20, 30)​
print("Length:", dimensions[0])
4. Functions in Tuples # Output: Length: 10

Although tuples are immutable, Python

E
provides various functions to work with them
Example 4: Counting Elements in a Tuple

EG
effectively.

len() - Returns the number of elements in a # Using count() to find


tuple.​

LL
occurrences​
fruits = ("apple", "banana",
colors = ("red", "green", "apple", "orange", "apple")​

O
"blue")​ print(fruits.count("apple")) #

C
print(len(colors)) # Output: 3 Output: 3
index() - Returns the index of the first
EE
occurrence of the specified element.​ Example 5: Tuple with Mixed Data Types
R

print(colors.index("green")) # # Creating a tuple with


EG

Output: 1 different data types​


student_info = ("John", 21,
count() - Counts the occurrences of a specified
element in the tuple.​ "Computer Science")​
.D

print(student_info) # Output:
('John', 21, 'Computer Science')
numbers = (1, 2, 2, 3, 4, 2)​
.M

print(numbers.count(2)) #
Output: 3 Dictionaries in Python
.P

A dictionary in Python is an unordered,


Example 1: List Slicing
IG

mutable collection of key-value pairs, where


each key is unique.
# Extracting sublist using slice​
R

languages = ["Python", "Java", Dictionaries are useful for storing and


organizing data that can be accessed by a
SH

"C++", "JavaScript"]​
specific identifier (key).
print(languages[1:3]) # Output:
['Java', 'C++'] Syntax:

Example 2: Accessing Elements in a Nested # Creating a dictionary​


List dictionary_name = {​
"key1": "value1",​
# Accessing elements in a nested "key2": "value2",​
list​ ...​
matrix = [​ }
[1, 2, 3],​
[4, 5, 6],​ Example:
8
# Example of a dictionary​ 'age': 20, 'grade': 'A'}
student = {​
"name": "Alice",​ Deletion Operator (del)
"age": 20,​
"course": "Computer Science"​ ○​Removes a specific key-value pair from
}​ the dictionary.

print(student)​ del student["age"]​
# Output: {'name': 'Alice', print(student)​
'age': 20, 'course': 'Computer # Output: {'name': 'Alice',
Science'} 'grade': 'A'}

E
Dictionaries can also be created using the Dictionary Methods

EG
dict() constructor:
Dictionaries come with several useful methods
for adding, modifying, and retrieving

LL
student = dict(name="Alice", key-value pairs.
age=20, course="Computer
Science")​ Common Dictionary Methods:

O
print(student)​
get() - Returns the value associated with a

C
# Output: {'name': 'Alice',
specified key. If the key does not exist, it
'age': 20, 'course': 'Computer
returns a default value (usually None).​
EE
Science'} ​
R

Operators in Dictionary print(student.get("name"))


EG

Dictionaries support several operators to check # Output: Alice​


for keys or update key-value pairs. print(student.get("age", "N/A"))
# Output: N/A (if 'age' is not
.D

Membership Operators (in, not in) found)

○​in - Checks if a specified key exists in keys() - Returns a list of all keys in the
.M

the dictionary. dictionary.​


○​not in - Checks if a specified key ​
.P

does not exist in the dictionary.


IG

print(student.keys()) # Output:
student = {"name": "Alice", dict_keys(['name', 'grade'])
"age": 20}​
values() - Returns a list of all values in the
R

print("name" in student) # dictionary.​


SH

Output: True​
print("grade" not in student) #
print(student.values()) #
Output: True
Output: dict_values(['Alice',
'A'])
Assignment Operator (=)
items() - Returns a list of all key-value
○​Used to add or update key-value pairs in pairs as tuples.​
the dictionary.
print(student.items()) #
student["grade"] = "A"​ Output: dict_items([('name',
print(student)​ 'Alice'), ('grade', 'A')])
# Output: {'name': 'Alice',

9
update() - Updates the dictionary with Example 3: Using get() with Default
another dictionary or a set of key-value pairs.​ Values

new_data = {"age": 21, "major": print(student.get("gender",


"Math"}​ "N/A")) # Output: N/A (if
student.update(new_data)​ 'gender' key does not exist)
print(student)​
# Output: {'name': 'Alice', Example 4: Iterating Over Keys and Values
'grade': 'A', 'age': 21,
'major': 'Math'} for key, value in
student.items():​
pop() - Removes the specified key and
print(key, ":", value)​

E
returns its value.​
# Output:​

EG
# name : Bob​
grade = student.pop("grade")​
# age : 23​
print(grade) # Output: A​
# major : Physics

LL
print(student) # Output:
{'name': 'Alice', 'age': 21,
Example 5: Using update() with New Data

O
'major': 'Math'}
clear() - Removes all items from the

C
student.update({"age": 24,
dictionary.​
"grade": "A"})​
EE
print(student) # Output:
student.clear()​ {'name': 'Bob', 'age': 24,
print(student) # Output: {}
R

'major': 'Physics', 'grade':


'A'}
EG

Examples of Dictionary Operations

Example 1: Accessing Values and Checking Using for Loop with Dictionaries
.D

for Keys
Types of Iteration in Dictionaries:
.M

# Checking for key existence​ 1.​ Looping Through Keys


student = {"name": "Bob", "age":
.P

22}​ Default iteration of a dictionary returns keys.


print("name" in student) #
IG

Output: True​ student = {"name": "Alice",


print("gender" in student) # "age": 20, "course": "CS"}​
for key in student:​
R

Output: False
print(key)​
SH

Example 2: Adding and Updating Entries # Output:​


# name​
# Adding and updating dictionary # age​
entries​ # course
student["major"] = "Physics"​
student["age"] = 23​ 2.​ Looping Through Values
print(student) # Output:
Use the .values() method to loop over all
{'name': 'Bob', 'age': 23,
values in the dictionary.
'major': 'Physics'}

for value in student.values():​


print(value)​
10
# Output:​ You can merge two dictionaries using the
.update() method or the | operator in
# Alice​
Python 3.9 and above.
# 20​
# CS
new_data = {"major": "Math",
"hobby": "Reading"}​
3.​ Looping Through Key-Value Pairs student.update(new_data)​
print(student)​
The .items() method returns key-value
pairs as tuples, allowing iteration over both # Output: {'name': 'Alice',
keys and values simultaneously. 'age': 21, 'grade': 'A',
'major': 'Math', 'hobby':
for key, value in 'Reading'}

E
student.items():​

EG
print(key, ":", value)​ 4.​ Clearing All Items
# Output:​
# name : Alice​ The .clear() method removes all items

LL
# age : 20​ from the dictionary, leaving it empty.
# course : CS

O
student.clear()​
print(student)​

C
Operations on Dictionaries
# Output: {}
1.​ Adding or Updating Items
EE
5.​ Copying a Dictionary
To add or update an item, assign a value to a
specific key. If the key already exists, the
R

Use .copy() to create a shallow copy of the


value is updated; otherwise, a new key-value dictionary.
EG

pair is added.
student_copy = student.copy()​
student["age"] = 21 #
.D

print(student_copy)​
Updating an existing key​
# Output: {'name': 'Alice',
student["grade"] = "A" #
'age': 21, 'grade': 'A',
.M

Adding a new key​


'major': 'Math', 'hobby':
print(student)​
'Reading'}
.P

# Output: {'name': 'Alice',


'age': 21, 'course': 'CS',
IG

'grade': 'A'} 6.​ Retrieving a Value with get()

get() is a safe way to retrieve a value for a


R

2.​ Removing Items key. It returns a default value if the key is


SH

missing, avoiding KeyError.


Use the del keyword or .pop() method to
remove items.
print(student.get("name", "Not
found")) # Output: Alice​
del student["course"]​
print(student.get("school", "Not
print(student)​
found")) # Output: Not found
# Output: {'name': 'Alice',
'age': 21, 'grade': 'A'}

Example 1: Looping Through Keys, Values,


3.​ Merging Dictionaries and Items

# Dictionary example​

11
product = {"name": "Laptop", Example 4: Clearing and Copying a
Dictionary
"price": 700, "brand": "Dell"}​

data = {"name": "Alice", "age":
# Looping through keys​
21}​
for key in product:​
data_copy = data.copy() #
print("Key:", key)​
Creating a copy​

data.clear() #
# Looping through values​
Clearing the original dictionary​
for value in product.values():​
print(data) #
print("Value:", value)​
Output: {}​

print(data_copy) #
# Looping through key-value

E
Output: {'name': 'Alice', 'age':
pairs​

EG
21}
for key, value in
product.items():​

LL
print(f"{key} -> {value}")
Example 5: Using get() to Access Values
Safely

O
Example 2: Adding, Updating, and Deleting
user = {"username": "jdoe",

C
Items
"email": "jdoe@example.com"}​
EE
inventory = {"apples": 10, print(user.get("username"))
"oranges": 15, "bananas": 5}​ # Output: jdoe​
inventory["grapes"] = 8 print(user.get("phone", "N/A"))
R

# Adding a new item​ # Output: N/A (since 'phone' key


EG

inventory["oranges"] = 20 does not exist)


# Updating an existing item​
del inventory["bananas"]
.D

# Removing an item​
print(inventory)​
.M

# Output: {'apples': 10,


'oranges': 20, 'grapes': 8}
.P
IG

Example 3: Merging Two Dictionaries


R

dict1 = {"name": "Alice", "age":


SH

25}​
dict2 = {"city": "New York",
"age": 26} # Existing key in
dict1 will be overwritten​

dict1.update(dict2)
# Merging dict2 into dict1​
print(dict1)​
# Output: {'name': 'Alice',
'age': 26, 'city': 'New York'}

12

You might also like