0% found this document useful (0 votes)
9 views

Disctionary in Python

Disctionary in Python

Uploaded by

royalcommunity43
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Disctionary in Python

Disctionary in Python

Uploaded by

royalcommunity43
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Dictionaries in Python

Dictionaries are a fundamental data structure in Python that store collections of


items in a key-value format. They are like phonebooks where you look up a
name (key) to find a phone number (value).

 Key-Value Pairs: Each item in a dictionary consists of a


unique key and an associated value. Keys act as identifiers for
accessing the corresponding values.
 Keys Must Be Immutable: Keys can be of various data types like
strings, numbers, or tuples, but they must be immutable
(unchangeable) to ensure efficient lookups. This is because
dictionaries use hashing to locate keys quickly. Lists, which are
mutable, cannot be used as keys.
 Values: Now, imagine the meaning of each word in the dictionary. In
Python, these meanings are called values. Each key in the dictionary has a
corresponding value.

So, let's say you want to create a dictionary to


store the ages of some people:

ages = {
"Paresh": 28,
"Harvinder": 20,
"Bob": 28
}
How Can Access Dictionaries Element
Accessing elements in Python dictionaries is
straightforward. You use the key to retrieve the
corresponding value. Here's how you can do it:

ages = {
"Paresh": 28,
"Harvinder": 20,
"Bob": 28
}

jage = ages["Paresh"]
print(jage)

You access elements in a dictionary by using


square brackets [] and providing the key inside.
If the key exists, it returns the corresponding
value.
If the key doesn't exist, it raises a Key Error, so
you can use the in keyword to check if the key
exists before accessing it.
Alternatively, you can use the get() method,
which returns None if the key doesn't exist,
allowing you to handle the absence of a key more
gracefully.
Accessing a non-existent key directly with square
brackets will raise a Key Error.

dictionary representing the ages of some people, and


we want to change the age of a specific person. Here's
how you can do it in Python:

# Define a dictionary with some initial


data
ages = {
"priya": 25,
"Sanjay": 30,
"Ramesh": 28,
"Emily": 35
}

# Print the original dictionary


print("Original dictionary:")
print(ages)

# Now, let's change the age of "Alice"


to 32
ages["priya"] = 32

# Print the updated dictionary


print("\nUpdated dictionary:")
print(ages)

We start with a dictionary called ages that contains the ages of


several people.
We print the original dictionary to see its contents.
To change the age of a person, we access the value associated
with their key (in this case, the key is "priya") using square
brackets [], and then assign a new value to it (32 in this
example).
After changing the value, we print the updated dictionary to
confirm the change.
So, in this example, we've successfully changed the age of
"paresh" from 30 to 32 in the dictionary. You can apply the same
method to change the value associated with any key in the
dictionary.

in Python, you can add key-value pairs to a


dictionary after it has been created using simple
syntax. Here's a brief example:
# Define an empty dictionary
ages = {}

# Print the original dictionary (empty)


print("Original dictionary:")
print(ages)

# Now, let's add some key-value pairs


to the dictionary
ages["Vishal"] = 25
ages["Jiya"] = 30
ages["priya"] = 28

# Print the upd ated dictionary


print("\nUpdated dictionary:")
print(ages)
Start with an empty dictionary: Imagine having
an empty box (dictionary) ready to store
information.

Check the original dictionary: Just making sure


the box is indeed empty before putting anything
inside.

Adding information: Now, we're putting stuff in


the box. We label each item with a key and write
down its corresponding value.

Confirm the changes: After putting things in the


box, we check again to see what's inside now.

Success!: We've filled the box with information.


And the great thing is, we can keep adding more
stuff whenever we want using the same method.
How Can Access key & Value

# Define an empty dictionary


ages = {}

# Print the original dictionary (empty)


print("Original dictionary:")
print(ages)

# Now, let's add some key-value pairs


to the dictionary
ages["vishal"] = 25
ages["jiya"] = 30
ages["priya"] = 28

# Print the updated dictionary


print("\nUpdated dictionary:")
print(ages)

# Accessing keys
print("The keys in the dictionary
are:", ages.keys())

# Accessing values
print("The values in the dictionary
are:", ages.values())

Nested Dictionaries
Imagine you have a regular dictionary in Python.
It's like a list of words in a dictionary, where each
word (key) has a definition (value). Now, let's say
you want to add more details to each definition.
That's where nested dictionaries come in.

A nested dictionary is like having mini-


dictionaries inside a big dictionary. Each mini-
dictionary has its own set of keys and values. So,
you have a main dictionary, and each value in
that dictionary is another dictionary.

In this example, student is a dictionary. It has


keys like "name" and "age", just like a regular
dictionary. But, it also has another key called
"grades", and the value of this key is another
dictionary. This inner dictionary contains grades
for different subjects.

So, to access the math grade of the student, you


would do:

python
Copy

# Main dictionary
student = {
"name": "John",
"age": 20,
"grades": {
"math": 90,
"science": 85,
"history": 88
}
}
math_grade = student["grades"]["math"]
print(math_grade)

How Can Check How Many Keys Present in my


Dictionaries
dictionary containing details about Indian states
and their populations. You want to count how
many states are included in the dictionary. Here's
a simple explanation in Python:

# Dictionary containing details about


Indian states and their populations
indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}

# Counting the number of states (i.e.,


counting the keys)
num_states = len(indian_states)
# Printing the count
print("Number of states in the
dictionary:", num_states)

In this example, len(indian_states) gives you the


number of keys in the dictionary indian_states,
which corresponds to the number of states.
Then, you simply print out the count.

Output :

Number of states in the dictionary: 5

This tells you that there are 5 keys (states) in the


dictionary.

Add new key :


Let's say you have a dictionary representing
Indian states and their populations, and you
want to add a new state along with its population
to the dictionary. Here's a simple explanation in
Python:
# Existing dictionary containing
details about Indian states and their
populations
indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}

# Adding a new state and its population


to the dictionary
indian_states["Rajasthan"] = 77264000

# Printing the updated dictionary


print("Updated Indian States
Dictionary:")
print(indian_states)

In this example, we're adding a new key-value


pair to the indian_states dictionary. The key is
"Rajasthan" and the value is 77264000,
representing the population of Rajasthan.

pop() method
pop() method is used to remove a specified key
and its associated value from a dictionary. Here's
a simple explanation with an example using
Indian state details:

Let's say you have a dictionary containing details


about Indian states and their populations. You
want to remove a state from the dictionary based
on its name.

indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}

# Removing a state from the dictionary


using pop()
removed_population =
indian_states.pop("Bihar")

# Printing the dictionary after


removing the state
print("Dictionary after removing
Bihar:", indian_states)
In this example, indian_states.pop("Bihar")
removes the key "Bihar" from the dictionary
indian_states and returns the value associated
with it, which is the population of Bihar. The
dictionary is then updated without the key
"Bihar".

dict.copy()

is a method in Python dictionaries that creates a


shallow copy of the dictionary. Here's a simple
explanation with an example using Indian state
names and their populations:

Suppose you have a dictionary indian_states


containing details about Indian states and their
populations:

indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}
indian_states_copy =
indian_states.copy()
indian_states_copy["Kerala"] = 35699443
print(indian_states);
print(indian_states_copy);

Now, indian_states_copy has the new state "Kerala" with its population, but
indian_states remains unchanged. This demonstrates that dict.copy() creates
an independent copy of the original dictionary.

deleting Elements using ‘del’ Keyword

dictionary with details about Indian states and


their populations, and you want to remove some
entries. Here's how you can do it using the del
keyword:

# Dictionary containing details about


Indian states and their populations
indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}

# Removing entries using 'del' keyword


del indian_states["Bihar"]
del indian_states["Madhya Pradesh"]

# Printing the updated dictionary


print("Updated dictionary after
removing entries:", indian_states)
in this example, del indian_states["Bihar"]
removes the entry for the state "Bihar" from the
indian_states dictionary, and del
indian_states["Madhya Pradesh"] removes the
entry for "Madhya Pradesh". After executing
these lines, the dictionary will no longer contain
the keys "Bihar" and "Madhya Pradesh" along
with their corresponding values.

You might also like