Placement Prep

Python Dictionaries: Operations, Methods, and Examples

Learn how Python dictionaries store key-value pairs: how to create, access, modify, delete, and iterate over them. Includes dict comprehensions and placement examples.

By FACE Prep Team 5 min read
python dictionaries data-structures placement-prep coding-programs crt-training

A Python dictionary maps each key to one value and retrieves it in O(1) time. Dict questions appear in every CRT coding portal from TCS NQT to AMCAT because of that lookup property.

This article covers the full operation set: creating, reading, modifying, deleting, iterating, and compressing loops into dict comprehensions. All code examples are verified from first principles.

What a Python Dictionary Is

A dictionary is a collection of key-value pairs. Each key is unique within a single dict. Keys must be immutable: strings, integers, floats, booleans, and tuples all qualify. Values can be anything: numbers, strings, lists, even other dicts.

The Python documentation on built-in types describes dicts as hash tables, which is why key lookup runs in O(1) average time regardless of how many pairs the dict holds. A list search scans from the front and runs in O(n) time. That performance difference is what makes dicts the right tool when you need to map an identifier to a value and look it up repeatedly.

Since Python 3.7, dicts preserve insertion order. If your code or your exam question assumes an unordered dict, it is referencing behaviour from Python 3.5 or earlier.

Basic syntax

# Literal syntax
student = {"name": "Priya", "branch": "CSE", "cgpa": 8.4}

# Empty dict
empty = {}

# Single pair
grade = {"maths": 92}

Creating Dictionaries

Python gives you three main ways to build a dict.

Literal syntax (most common)

profile = {"name": "Arjun", "college": "PSG Tech", "year": 3}
print(profile)
# Output: {'name': 'Arjun', 'college': 'PSG Tech', 'year': 3}

The dict() constructor

profile = dict(name="Arjun", college="PSG Tech", year=3)
print(profile)
# Output: {'name': 'Arjun', 'college': 'PSG Tech', 'year': 3}

Note: dict() with keyword arguments only works when keys are valid Python identifiers (no spaces, no hyphens).

From a list of tuples

pairs = [("a", 1), ("b", 2), ("c", 3)]
d = dict(pairs)
print(d)
# Output: {'a': 1, 'b': 2, 'c': 3}

This pattern appears in placement MCQs. Know that dict() accepts any iterable of two-element iterables.

The duplicate-key trap

When you define the same key twice, the second value silently overwrites the first:

d = {"color": "pink", "color": "red"}
print(d)
# Output: {'color': 'red'}

This is a common MCQ trap in CRT coding portals. The output is not an error; it is the last-assigned value.

Reading, Modifying, and Deleting Values

Reading a value

student = {"name": "Meera", "branch": "ECE", "cgpa": 7.9}

# Bracket access — raises KeyError if key is absent
print(student["name"])        # Output: Meera

# get() — returns None (or a default) if key is absent
print(student.get("name"))               # Output: Meera
print(student.get("company", "Not placed yet"))  # Output: Not placed yet

Use d["key"] when the key must exist (you want an error if it does not). Use d.get("key", default) when the key might be absent and you want a safe fallback.

Adding and modifying values

student = {"name": "Meera", "branch": "ECE"}

# Add a new key
student["cgpa"] = 7.9
print(student)
# Output: {'name': 'Meera', 'branch': 'ECE', 'cgpa': 7.9}

# Modify an existing key
student["branch"] = "EEE"
print(student)
# Output: {'name': 'Meera', 'branch': 'EEE', 'cgpa': 7.9}

The syntax for adding a new key and for updating an existing key is identical. Python checks whether the key already exists; if it does, the value is overwritten.

Deleting values

Three tools, three different behaviours:

d = {"color": "pink", "shape": "square", "size": "small"}

# pop() — removes one key and returns its value
removed = d.pop("color")
print(removed)  # Output: pink
print(d)        # Output: {'shape': 'square', 'size': 'small'}

# del — removes one key; no return value
del d["shape"]
print(d)        # Output: {'size': 'small'}

# clear() — removes all keys; dict still exists as an empty object
d.clear()
print(d)        # Output: {}

del dict_name (without a key) deletes the variable entirely. Attempting to use it afterwards raises a NameError.

Useful Dictionary Methods

The Python tutorial section on dictionaries lists all built-in methods. The eight that appear most often in placement assessments:

MethodWhat it doesReturns
keys()All keys as a view objectdict_keys
values()All values as a view objectdict_values
items()All key-value pairs as a view objectdict_items
get(key, default)Value for key, or default if absentvalue or default
update(other)Merges another dict into this oneNone
pop(key)Removes key and returns its valuevalue
popitem()Removes last inserted pair, returns it(key, value) tuple
clear()Empties the dictNone

Iteration patterns

scores = {"aptitude": 85, "coding": 70, "verbal": 90}

# Iterate over keys (default)
for subject in scores:
    print(subject)

# Iterate over values
for score in scores.values():
    print(score)

# Iterate over key-value pairs
for subject, score in scores.items():
    print(f"{subject}: {score}")

items() is the one to memorise for placement rounds. Most dict-loop questions ask for both key and value at once.

The update() method

base = {"name": "Vikram", "branch": "IT"}
extra = {"cgpa": 8.1, "year": 4}
base.update(extra)
print(base)
# Output: {'name': 'Vikram', 'branch': 'IT', 'cgpa': 8.1, 'year': 4}

If a key exists in both dicts, update() overwrites with the value from the argument dict.

Dict Comprehensions

A dict comprehension builds a dictionary in one expression. The syntax mirrors list comprehensions but uses curly braces and a colon to separate key from value.

# Squares of numbers 1 through 5
squares = {n: n**2 for n in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

With a filter condition

# Only even numbers
even_squares = {n: n**2 for n in range(1, 11) if n % 2 == 0}
print(even_squares)
# Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Inverting a dict

original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
# Output: {1: 'a', 2: 'b', 3: 'c'}

Inversion only works safely when every value in the original dict is unique. Duplicate values result in silent key loss.

Practical placement use case

In the calculator program, operators are dispatched via if-elif chains. A dict maps each operator string directly to a function, which is a cleaner pattern interviewers notice. That dispatch approach and other dict-centric patterns are also covered in the Python basic programs practice set.

When Dicts Beat Lists

Use a dict when:

  • You need to look up a value by a meaningful identifier (name, ID, label), not by position.
  • The lookup will happen many times — O(1) dict access vs. O(n) linear scan for a list.
  • You need to associate two pieces of data: a key and a value.

Use a list when:

  • Order and position matter (index 0 is “first”).
  • You need slicing.
  • Elements are homogeneous and have no named identity.

The sum of array elements example shows where a list is the right tool. Position matters there, and you are accumulating a single total. Replacing that list with a {index: value} dict adds complexity without adding value.


Querying a dict with get(), iterating with items(), and compressing build loops into comprehensions are the exact patterns that appear when working with LLM API responses. Every API call returns JSON, which Python loads as a plain dict. If you want to try that yourself before building a project around it, TinkerLLM starts at ₹299 and gives you a live environment to send prompts and inspect the response objects directly.

Primary sources

Frequently asked questions

What types can be used as dictionary keys in Python?

Keys must be immutable: strings, integers, floats, booleans, and tuples all work. Lists and dicts cannot be keys because they are mutable and therefore unhashable.

What is the difference between d['key'] and d.get('key')?

Bracket access raises a KeyError if the key does not exist. d.get('key') returns None by default, or a value you specify as the second argument, for example d.get('color', 'unknown').

Are Python dictionaries ordered?

Yes, since Python 3.7 insertion order is guaranteed and preserved. Earlier versions treated dicts as unordered, which is why older tutorials still warn about ordering.

How do I merge two dictionaries in Python?

Use d1.update(d2) to merge d2 into d1 in place, overwriting any shared keys. For a new dict without modifying either original, use {**d1, **d2}. Python 3.9 and later also support the | merge operator: d1 | d2.

How do I check if a key exists in a Python dictionary?

Use 'key' in my_dict. This returns True or False in O(1) time without raising an exception, unlike trying to access the key directly.

What does popitem() do in a Python dictionary?

popitem() removes and returns the last inserted key-value pair as a (key, value) tuple. Calling it on an empty dict raises a KeyError.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF