Understanding Python Dictionaries

Understanding Python Dictionaries

Have you ever thought about how your computer knows where to find your favorite game or how your phone stores your contacts?

One of the coolest and most useful data structures in Python is the dictionary.

Imagine having a magical notebook where you can look up any information instantly. That's what a Python dictionary is like!


What is a Python Dictionary ?

A Python dictionary is a collection of key-value pairs.

Think of it as a real-life dictionary, where you look up a word (the key) to find its meaning (the value).

Unlike a real dictionary, though, a Python dictionary can hold any kind of information : numbers, strings, lists, even other dictionaries!


Creating a Dictionary

Creating a dictionary in Python is simple.

Here's how you do it :

# Creating an empty dictionary
my_dict = {}

# Creating a dictionary with some key-value pairs
student_info = {
    "name": "Sky",
    "age": 14,
    "grade": "8th"
}        

In the "student_info" dictionary, "name", "age", and "grade" are the keys, and "Sky", 14, and "8th" are their respective values.


Accessing Values

To get the value associated with a key, you use square brackets:

print(student_info["name"])  
print(student_info["age"])           

Output :

Sky
14        

If you try to access a key that doesn’t exist, you’ll get an error. To avoid this, you can use the get method, which returns None (or a default value) if the key isn’t found:

print(student_info.get("hobby", "Not specified"))          

Output :

Not specified        

Adding and Updating Values

Adding a new key-value pair is easy. Just use a new key and assign it a value:

student_info["hobby"] = "painting"
print(student_info)  
        

Output :

{'name': 'Sky', 'age': 14, 'grade': '8th', 'hobby': 'painting'}        

You can also update the value of an existing key:

student_info["grade"] = "9th"
print(student_info)          

Output :

 {'name': 'Sky', 'age': 14, 'grade': '9th', 'hobby': 'painting'}        

Removing Items

You can remove a key-value pair using the del keyword or the pop method:

del student_info["hobby"]
print(student_info)  

grade = student_info.pop("grade")
print(student_info)  
print(grade)         
        

Output :

 {'name': 'Sky', 'age': 14, 'grade': '9th'} 
 {'name': 'Sky', 'age': 14} 
 9th        

Looping Through a Dictionary

To loop through a dictionary, you can use a for loop. You can loop through the keys, the values, or both:

# Looping through keys
for key in student_info:
    print(key)

# Looping through values
for value in student_info.values():
    print(value)

# Looping through key-value pairs
for key, value in student_info.items():
    print(f"{key}: {value}")
        

Examples of Python Dictionaries in Action


Example 1 : Contact List

Imagine you want to store contact information for your friends:

contacts = {
    "John": "123-456-7890",
    "Jane": "987-654-3210",
    "Bob": "555-555-5555"
}

# Accessing a contact number
print(contacts["Jane"])  
        

Output:

987-654-3210        

Example 2 : Shopping Cart

A shopping cart can be represented as a dictionary, where the keys are the item names and the values are their prices:

shopping_cart = {
    "apple": 0.5,
    "banana": 0.3,
    "milk": 1.5
}

# Calculating the total cost
total_cost = sum(shopping_cart.values())
print(f"Total cost: ${total_cost}") 
        

Output:

 Total cost: $2.3        

Example 3 : Student Grades

You can store students' grades in a dictionary:

grades = {
    "Sky": "A",
    "Bob": "B",
    "Charlie": "C"
}

# Printing each student's grade
for student, grade in grades.items():
    print(f"{student}: {grade}")
        

Now that you know the basics of Python dictionaries, it's time to start experimenting. Try creating your own dictionaries and see how they can make managing data easier and more fun.

Whether you're storing contact info, shopping lists, or anything else, dictionaries are a powerful tool to have in your Python toolkit.


Remember, this isn't a guide or tutorial—I'm just sharing what I've learned.

If you found this interesting and want more insights into Python or have any questions, feel free to like and comment below.


Let's connect and learn more about Python together!


Happy coding!

Rahul K

Student at Bangalore North University

2 个月

Very informative

要查看或添加评论,请登录

Subhash Kumar Yadav的更多文章

  • Understanding Python Statements : A Simple Explanation

    Understanding Python Statements : A Simple Explanation

    Hello, Imagine if you could create your own digital world just by writing a few lines of code. What if you could make a…

    3 条评论
  • Python Functions Explained : A Simple Guide for Beginners

    Python Functions Explained : A Simple Guide for Beginners

    Hello , Have you ever wondered how Python functions can make your coding life easier ? Imagine having a magical tool…

    2 条评论
  • What Are Operators and How Do We Use Them ?

    What Are Operators and How Do We Use Them ?

    Ever wondered how computers do math and logic ? It's all thanks to operators! Operators in Python are special symbols…

    1 条评论
  • Understanding Lists in Python.

    Understanding Lists in Python.

    Python is a popular programming language known for its simplicity and versatility. One of the most powerful features in…

  • Understanding Python Data Types

    Understanding Python Data Types

    Python is a versatile and powerful programming language that is widely used for various applications, from web…

    1 条评论
  • Understanding Variables in Python

    Understanding Variables in Python

    What is a Variable ? In programming, a variable is like a box with a label on it. You can put different pieces of…

    1 条评论
  • Story of Python: A Magic Language That Changes the World.

    Story of Python: A Magic Language That Changes the World.

    Hello, Today, let's travel through the magical world of Python, a special language that has done amazing things and…

  • Introduction to Python Programming

    Introduction to Python Programming

    Python is a versatile and widely-used programming language known for its simplicity, readability and robustness…

    2 条评论
  • The Story of Python: A Magic Language That Changes the World.

    The Story of Python: A Magic Language That Changes the World.

    Hello, Today, let's travel through the magical world of Python, a special language that has done amazing things and…

社区洞察

其他会员也浏览了