Mastering Dictionaries in Python: A Beginner's Guide

Harsh GuptaHarsh Gupta
3 min read

A dictionary in Python is a collection of key-value pairs. It is unordered, mutable, and indexed by keys — which can be strings, numbers, or even tuples (if immutable).

Let’s begin exploring with the Python shell open.

lang = {
    "c++": "easy",
    "java": "difficuilt",
    "javascript": "medium"
}

Accessing Dictionary Items

You can access a value by its key:

print(lang["javascript"])  # Outputs: medium

Or use the safer .get() method:

print(lang.get("javascript"))  # Outputs: medium

But what if the key doesn't exist?

print(lang.get("javascripttt"))  # Outputs: None
print(lang["javascripttt"])      # Throws KeyError ❌

🧠 .get() is safer because it doesn’t crash your program.

Updating Dictionary Items

You can update the value of a key like this:

lang["java"] = "god level"
print(lang)
# {'c++': 'easy', 'java': 'god level', 'javascript': 'medium'}

Looping Through a Dictionary

  1. Looping over keys:
for item in lang:
    print(item)

#Outputs: c++
#         java
#         javascript

2. Looping Over Values:

for item in lang:
    print(lang[item])

#Outputs: easy
#         god level
#         medium
  1. Looping over keys and values:

when we are looping over the dictionary, we are allowed to inject one more variable, but we have to change the syntax a bit, we can give dictionary name directly, now we have to access each item like this:

for key, value in lang.items():
    print(key, value)

#Outputs: c++ easy
#         java god level
#         javascript medium

Check If Key Exists

we can also check if certain key is present in dictionary

if "java" in lang:
    print("java is present in dictionary")

✅ Output: java is present in dictionary

Length of Dictionary

print(len(lang))  # Outputs: 3

Adding and Removing Items

Add a New Item:

lang["rust"] = "threads opener"
print(lang) #outputs:  {'c++': 'easy', 'java': 'god level', 'javascript': 'medium', 'rust': 'threads opener'}

Remove by key:

we can also use pop method in dictionary, but we have to provide key name, because there is no order in the dictionary, also it returns the value of that particular key that has been removed

lang.pop("java")
print(lang) #Outputs: {'c++': 'easy', 'javascript': 'medium', 'rust': 'threads opener'}

Remove the last inserted item:

lang.popitem()
# returns: ('rust', 'threads opener')
print(lang) #Outputs:  {'c++': 'easy', 'javascript': 'medium'}

Deleting using “del“:

del lang["javascript"]
print(lang) #Outputs: {'c++': 'easy'}

Copying a Dictionary

lang_copy = lang

Now lang_copy and lang point to the same reference, changes inside lang_copy will also be reflected inside lang.

solution for this:

lang_copy = lang.copy()

This creates a shallow copy that won’t affect the original when modified, now they both point to the different reference.

Nested Dictionaries

subjects = {
    "lang": {
        "c++": "easy",
        "javascript": "medium",
        "java": "difficuilt"
    },
    "general": {
        "english": "easy",
        "science": "medium",
        "maths": "hard"
    },
    "optional": "IT"
}

print(subjects) #outputs: {'lang': {'c++': 'easy', 'javascript': 'medium', 'java': 'difficuilt'}, 'general': {'english': 'easy', 'science': 'medium', 'maths': 'hard'}, 'optional': 'IT'}

Access nested values:

subjects["lang"]
#Outputs: {'c++': 'easy', 'javascript': 'medium', 'java': 'difficuilt'}

#to be more specific
subjects["lang"]["c++"]
#outputs: easy

Dictionary Comprehension

Just like list comprehension, Python supports dictionary comprehension:

squared_num = {x: x**2 for x in range(6)}
print(squared_num)
# Outputs: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

#clearing a dictionary
squared_num.clear()
print(squared_num)  # Outputs: {}

Creating Dictionary from List

Let's say you have a list of keys and want to assign a default value to all of them:

keys = ["c++", "java", "python"]
default_value = "medium"

new_dict = dict.fromkeys(keys, default_value)
print(new_dict)
# {'c++': 'medium', 'java': 'medium', 'python': 'medium'}

Final Thoughts

Dictionaries are one of Python’s most powerful and flexible data structures. Whether you're tracking user data, building APIs, or storing configurations — mastering dictionaries is a must.

0
Subscribe to my newsletter

Read articles from Harsh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harsh Gupta
Harsh Gupta

I am a CSE undergrad learning DevOps and sharing what I learn.