Today, we're going to learn about dictionaries.
Dictionaries are like special containers that can hold lots of
information. They are used to store data values in key-value pairs.
Think of a key-value pair as a special pair of friends. Every key has a special friend called a value. Just like in
real life, where we have names (keys) and their corresponding friends (values). For example, if the key is
"fruit" then the value could be "apple".
. It's just like a real dictionary that you use to look up words and find their meanings. But instead of words and
meanings, we use something called "key-value" pairs.
SYNTAX….
Creating a dictionary is as simple as putting key-value pairs inside curly brackets {}. Let's say we want to create
a dictionary to store fruits and their colors. We can write it like this:
To create a dictionary, we use curly brackets, which look like this: {}. It's like having a special box to hold our
things.
my_dictionary = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}
Here, we have three key-value pairs.
The keys are "apple," "banana," and "grape," and their respective values are "red," "yellow," and "purple."
what about the colon and comma?
The colon : is like a separator that tells us that what comes before it is the key, and what comes after it is the
value for that key. It's like a little bridge that connects them.
The comma , is like a separator that tells us that we're moving on to the next key-value pair. It helps us keep
everything organized.
Teacher: Exactly! If we have more information to store, we can add more key-value pairs by separating them
with commas.
Let's say we want to add the key-value pair for "orange." We can do it like this:
my_dictionary = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple', 'orange': 'orange'}
EXAMPLE
D = {'name': 'Bob',
'age': 25,
'job': 'Dev',
'city': 'New York',
'email': 'bob@web.com'}
In this example, we have created a dictionary named D to store information about an
employee. The dictionary contains several key-value pairs. Let's go through each key-
value pair and explain them:
This dictionary is created to store information about an employee. Let's go through each key-value pair and
understand what they represent.
'name': 'Bob': The key is 'name', and the corresponding value is 'Bob'. Here, we are storing the
employee's name as a string.
'age': 25: The key is 'age', and the value is 25. We are storing the employee's age as a number
(integer).
'job': 'Dev': The key is 'job', and the value is 'Dev'. This represents the employee's job title or role,
stored as a string.
'city': 'New York': The key is 'city', and the value is 'New York'. Here, we are storing the city where the
employee lives, represented as a string.
'email': 'bob@web.com': The key is 'email', and the value is 'bob@web.com'. This key-value pair
stores the employee's email address as a string.
So, this dictionary is a collection of different pieces of information about an employee. The keys ('name', 'age',
'job', 'city', 'email') act as labels or identifiers, and the corresponding values store the actual data associated
with those labels.
We can access the values in the dictionary by using the keys as indexes. For example, if we want to retrieve
the employee's name, we can use D['name'], which will give us the value 'Bob'.
Code
print(D['name']) # Output: Bob
# Create an empty dictionary
courses={}
print(courses)
# Output:
# {}
In this code, we are creating an empty dictionary called courses. The dictionary
is assigned to an empty set of curly braces {}.
courses = {}
The print statement is then used to display the contents of the courses
dictionary:
print (courses)
Since we haven't added any key-value pairs yet, the output will be an empty set
of curly braces: {}.
EXAMPLE
Value can be of any type:
There are no restrictions on dictionary values. A dictionary value can be any type
of object
# Create dictionary with integer keys
courses={1:'java',2:'python',3:'panda'}
print(courses)
# create dictionary using dict()method
courses=dict({1:'Apple',2:'Orange',3:'Grapes'})
print(courses)
# Creating dictionary in which each item as a Pair
courses=dict([(1,'java'),(2,'python'),(3,'panda')])
print(courses)
Example 1: Create a dictionary with integer keys
courses = { 1 : 'java' , 2 : 'python' , 3 : 'panda' } print (courses)
In this example, we are creating a dictionary named courses with integer keys and
string values. The keys 1, 2, and 3 map to the respective values 'java', 'python', and
'panda'. The dictionary is then printed, resulting in the output: {1: 'java', 2: 'python',
3: 'panda'}.
Example 2: Create a dictionary using the dict() method
courses = dict ({ 1 : 'Apple' , 2 : 'Orange' , 3 : 'Grapes' }) print (courses)
In this example, we are using the dict() method to create a dictionary named courses.
The method is passed a dictionary literal {1: 'Apple', 2: 'Orange', 3: 'Grapes'} with integer
keys and string values. The dictionary is then printed, resulting in the output: {1:
'Apple', 2: 'Orange', 3: 'Grapes'} .
Example 3: Creating a dictionary with key-value pairs as a list of tuples
courses = dict ([( 1 , 'java' ), ( 2 , 'python' ), ( 3 , 'panda' )]) print (courses)
In this example, we are creating a dictionary named courses by passing a list of
tuples to the dict() method. Each tuple in the list represents a key-value pair. In this
case, the keys are integers 1, 2, and 3, and the values are strings 'java',
'python', and 'panda'. The dictionary is then printed, resulting in the output:
{1: 'java', 2: 'python', 3: 'panda'}.
Overall, these examples demonstrate different ways to create dictionaries in Python.
Dictionaries are flexible data structures that allow you to map keys to values. The keys
can be of any immutable type (such as integers, strings, or tuples), and the values can
be of any type, including built-in types (like integers, strings, lists, etc.) or custom
objects.
ACCESSING DICT
Dictionary is an unordered collection, so a value cannot be accessed
using an index; instead, a key must be specified in the square brackets,
as shown below. the values can access in the dictionary by using the
keys. Python provides two different ways of using a key to access the
values of the dictionary, which are inside square brackets [] or with the
get() method.
To access values in a Python dictionary, you can use the keys as the index within
square brackets ([]). Here's an example:
# Create a dictionary
student = {"name": "John", "age": 20, "grade": "A"}
# Access values using keys
print(student["name"]) # Output: John
print(student["age"]) # Output: 20
print(student["grade"]) # Output: A
In the above example, we have a dictionary called student with keys "name", "age",
and "grade", and their respective values. To access the values, we use the keys within
square brackets after the dictionary name. The expressions student["name"],
student["age"], and student["grade"] return the corresponding values "John", 20, and
"A".
If you try to access a key that does not exist in the dictionary, it will raise a KeyError.
To avoid this, you can use the get() method, which allows you to specify a default
value to be returned if the key is not found:
# Access values using get() method
print(student.get("name")) # Output: John
print(student.get("gender")) # Output: None
In the above code, student.get("name") returns the value associated with the key
"name",
while student.get("gender") returns None since the key "gender" doesn't exist in the
dictionary.
By providing a default value as the second argument to get(), you can specify a value
to be returned when the key is not found. In this case, student.get("gender", "-")
returns "-" as the default value instead of None.
TRYYYY LIVE
: Can a dictionary have duplicate keys?
Output: No, a dictionary cannot have duplicate keys. If you try to assign a value to an existing key, it will
update the existing value rather than creating a duplicate key. For example:
my_dictionary = {'a': 1, 'b': 2, 'a': 3}
print(my_dictionary)
Output: {'a': 3, 'b': 2}
Q: What happens if you try to access a key that doesn't exist in a dictionary? Explain with an example.
Output: If you try to access a key that doesn't exist in a dictionary, it will raise a KeyError. For example:
my_dictionary = {'a': 1, 'b': 2}
print(my_dictionary['c'])
Output: KeyError: 'c'
Add Elements to a Python Dictionary
To add elements to a Python dictionary, you can assign a value to a new key or an
existing key using the assignment operator (=). Here are a few ways to add elements
to a dictionary:
# Create an empty dictionary
student = {}
# Add elements using assignment
student["name"] = "John"
student["age"] = 20
student["grade"] = "A"
print(student)
In the above example, an empty dictionary student is created. The elements are
added by assigning values to the corresponding keys using the assignment operator
(=). After adding the elements, the dictionary is printed, resulting in the output:
{'name': 'John', 'age': 20, 'grade': 'A'}
You can also add elements to an existing dictionary using the same method:
# Create a dictionary with existing elements
student = {"name": "John", "age": 20}
# Add new elements
student["grade"] = "A"
student["city"] = "New York"
print(student)
In this case, the dictionary student already contains the elements "name" and "age".
We can add new elements "grade" and "city" by assigning values to these keys. The
output will be:
{'name': 'John', 'age': 20, 'grade': 'A', 'city': 'New York'}
If the key already exists in the dictionary, assigning a new value to that key will update
the existing value:
# Create a dictionary
student = {"name": "John", "age": 20}
# Update an existing element
student["age"] = 21
print(student)
In this example, the value associated with the key "age" is updated from 20 to 21. The
output will be:
{'name': 'John', 'age': 21}
Adding elements to a dictionary is a straightforward process, and you can dynamically
expand the dictionary as needed by assigning values to new or existing keys.
EXAMPLE……………
#creating an empty dictionary
my_dictionary={}
print(my_dictionary)
#adding elements to the dictionary one at a time
my_dictionary[1]="James"
my_dictionary[2]="Jim"
my_dictionary[3]="Jake"
print(my_dictionary)
#modifying existing entry
my_dictionary[2]="Apple"
print(my_dictionary)
#adding multiple values to a single key
my_dictionary[4]="Banana,Cherry,Kiwi"
print(my_dictionary)
#adding nested key values
my_dictionary[5]={'Nested' :{'1' : 'Scaler', '2' : 'Academy'}}
print(my_dictionary)
Sure! Let's go through each step and explain it:
# Creating an empty dictionary
my_dictionary = {}
print(my_dictionary)
In this step, an empty dictionary named my_dictionary is created by using empty
curly braces ({}). The dictionary is then printed, resulting in an empty output: {}.
# Adding elements to the dictionary one at a time
my_dictionary[1] = "James"
my_dictionary[2] = "Jim"
my_dictionary[3] = "Jake"
print(my_dictionary)
In this step, we add elements to the dictionary one at a time. Each element consists
of a key-value pair.
For example,
my_dictionary[1] = "James" assigns the value "James" to the key 1 in the dictionary.
Similarly, my_dictionary[2] = "Jim" assigns the value "Jim" to the key 2, and
my_dictionary[3] = "Jake" assigns the value "Jake" to the key 3. After adding these
elements, the dictionary is printed, resulting in the output:
\
{1: 'James', 2: 'Jim', 3: 'Jake'}
# Modifying an existing entry
my_dictionary[2] = "Apple"
print(my_dictionary)
In this step, we modify an existing entry in the dictionary.
The assignment
my_dictionary[2] = "Apple" updates the value associated with the key 2 from "Jim"
to "Apple".
The dictionary is then printed, resulting in the output:
{1: 'James', 2: 'Apple', 3: 'Jake'}
# Adding multiple values to a single key
my_dictionary[4] = "Banana, Cherry, Kiwi"
print(my_dictionary)
Here, we add a key-value pair where the value is a string containing multiple values
separated by commas. The assignment my_dictionary[4] = "Banana, Cherry, Kiwi"
assigns the string "Banana, Cherry, Kiwi" to the key 4. The dictionary is printed,
resulting in the output:
{1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana, Cherry, Kiwi'}
Overall, this code snippet demonstrates various ways to add elements to a
dictionary, including adding elements one at a time, modifying existing entries,
adding multiple values to a single key, and adding nested key-value pairs.
DELETE
my_dictionary = {1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
del my_dictionary[4]
print(my_dictionary)
You are deleting an element from the dictionary using the del statement and then
printing the updated dictionary.
In the line del my_dictionary[4], you are using the del statement to remove the key-
value pair with the key 4 from the my_dictionary.
After executing this line, the key-value pair 4: 'Banana,Cherry,Kiwi' will no longer
exist in the dictionary.
Finally, you print the updated dictionary using print(my_dictionary). The output will
be:
{1: 'James', 2: 'Apple', 3: 'Jake'}
As you can see, the key-value pair with the key 4 and the corresponding value
'Banana,Cherry,Kiwi' has been successfully deleted from the dictionary.
LENGTH
That's correct! To determine the number of items (key-value pairs) in a dictionary,
you can use the len() function. Here's an example:
my_dictionary = {1: 'James', 2: 'Apple', 3: 'Jake', 4: 'Banana,Cherry,Kiwi'}
# Get the length of the dictionary
length = len(my_dictionary)
# Print the length
print(length)
In this example, the len() function is used to calculate the length of the dictionary
my_dictionary. The resulting length is stored in the variable length. Finally, the value
of length is printed, which represents the number of items in the dictionary.
The output will be:
4
In this case, the dictionary my_dictionary contains four key-value pairs, so the
length of the dictionary is 4.