Disctionary in Python
Disctionary in Python
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)
# 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.
python
Copy
# Main dictionary
student = {
"name": "John",
"age": 20,
"grades": {
"math": 90,
"science": 85,
"history": 88
}
}
math_grade = student["grades"]["math"]
print(math_grade)
Output :
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:
indian_states = {
"Maharashtra": 112374333,
"Uttar Pradesh": 199812341,
"Bihar": 104099452,
"West Bengal": 91276115,
"Madhya Pradesh": 72626809
}
dict.copy()
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.