Python Dictionaries

Learn about dictionaries in Python - ordered collections of key-value pairs.

Dictionaries

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Dictionaries are written with curly brackets, and have keys and values:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}
print(thisdict)

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Example

print(len(thisdict))

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example

thisdict = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

type()

From Python's perspective, dictionaries are defined as objects with the data type 'dict':

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(type(thisdict))

Accessing Items

You can access the items of a dictionary by referring to its key name, inside square brackets:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same result:

Example

x = thisdict.get("model")

Get Keys

The keys() method will return a list of all the keys in the dictionary.

Example

x = thisdict.keys()

Get Values

The values() method will return a list of all the values in the dictionary.

Example

x = thisdict.values()

Get Items

The items() method will return each item in a dictionary, as tuples in a list.

Example

x = thisdict.items()

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

Change Values

You can change the value of a specific item by referring to its key name:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

Update Dictionary

The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"year": 2020})

Adding Items

Adding an item to the dictionary is done by using a new index key and assigning a value to it:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary

The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.update({"color": "red"})

Removing Items

There are several methods to remove items from a dictionary:

The pop() method

The pop() method removes the item with the specified key name:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

The popitem() method

The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

The del keyword

The del keyword removes the item with the specified key name:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

The del keyword can also delete the dictionary completely:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

The clear() method

The clear() method empties the dictionary:

Example

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)

Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example - Print all key names in the dictionary, one by one:

for x in thisdict:
  print(x)

Example - Print all values in the dictionary, one by one:

for x in thisdict:
  print(thisdict[x])

Example - You can also use the values() method to return values of a dictionary:

for x in thisdict.values():
  print(x)

Example - You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
  print(x)

Example - Loop through both keys and values, by using the items() method:

for x, y in thisdict.items():
  print(x, y)

Safe Access with get()

Indexing a missing key raises KeyError. get() returns a default instead.

person = {"name": "John", "age": 36}

# print(person["city"])       # KeyError!
print(person.get("city"))      # None
print(person.get("city", "Unknown"))   # Unknown
print("age" in person)         # True

Looping Over a Dictionary

person = {"name": "John", "age": 36}

for key in person:                 # keys
    print(key)

for value in person.values():      # values
    print(value)

for key, value in person.items():  # both
    print(f"{key} = {value}")

Dict Comprehensions and Counting

squares = {n: n ** 2 for n in range(5)}   # {0:0, 1:1, 2:4, 3:9, 4:16}

# count letters
from collections import Counter
print(Counter("banana"))   # Counter({'a': 3, 'n': 2, 'b': 1})

# merge two dicts (Python 3.9+)
a = {"x": 1}; b = {"y": 2}
print(a | b)               # {'x': 1, 'y': 2}

Since Python 3.7, dictionaries remember insertion order — iterating gives keys back in the order you added them.

Try It Yourself

Exercise 1: Given prices = {"apple": 3, "pear": 4}, safely print the price of "banana" as 0 if missing.

Show solution
prices = {"apple": 3, "pear": 4}
print(prices.get("banana", 0))   # 0

Exercise 2: Count how often each character appears in "mississippi".

Show solution
from collections import Counter
print(Counter("mississippi"))
# Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})

Key Takeaways

  • Dicts map unique, hashable keys to values with O(1) lookup.
  • Use get(key, default) to avoid KeyError.
  • Iterate with .items() for key/value pairs.
  • Dicts keep insertion order; Counter tallies effortlessly.

📘 Real-World Deep Dive

Dictionaries are Python's most-used mapping. Knowing how to pick keys, merge maps, default values, and switch between dict-of-dicts and flat records is essential.

Real-Life Scenario

A two-pass word-count + top-N finder over a stream of log messages — counts in a dict, then sorted into the leaderboard.

Real-Life Example

import re
from collections import Counter

WORD_RX = re.compile(r"[A-Za-z][A-Za-z\'-]+")

def stream_lines(path):
    with open(path) as f:
        for line in f:
            yield line

def top_words(path: str, n: int = 5) -> list[tuple[str, int]]:
    counts: Counter[str] = Counter()
    for line in stream_lines(path):
        for word in WORD_RX.findall(line.lower()):
            counts[word] += 1
    return counts.most_common(n)

for w, c in top_words("posts.txt", n=8):
    print(f"{w:>10}  {c}")

Expected Output

     python  342
    django  218
  tutorial  198
        pip  142
  beginner  121
     server   98
     script   81
      async   72

Common mistakes

  • Accessing a missing key with d["k"] raises KeyError. Use d.get("k", default) or collections.defaultdict.
  • Mutating a dict while iterating it raises RuntimeError — snapshot keys with list(d) first.
  • Don't use dict as a substitute for a database — there's no schema, no indexing, no concurrent-safety.

🚀 Performance & Best Practices

  • Lookups are amortised O(1). Use dict instead of searching a list in a hot path.
  • d.setdefault(k, []).append(v) builds the same list every call — switch to defaultdict(list).
  • For huge dicts, consider cython-backed alternatives like pandas.Series with a string index.

🧪 Try It Yourself

  1. Return both top_words and the unique-word count in one pass.
  2. Sort the result alphabetically when ties occur.
  3. Profile Counter vs. defaultdict(int).

FAQ: Python Dictionaries

Common questions about this page.

What is Python Dictionaries?

Python Dictionaries is a Python Tutorial lesson that explains python dictionaries in Python. Learn about dictionaries in Python - ordered collections of key-value pairs. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python dictionaries examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python dictionaries in this Python Tutorial Python lesson (Python Dictionaries).

How do I use python dictionaries in Python?

To use python dictionaries in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python dictionaries?

This Python Dictionaries tutorial shows python dictionaries syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Dictionaries example for beginners

Yes. This page includes a beginner python dictionaries example you can copy and run. It is designed for searches such as "python dictionaries for beginners", "python dictionaries example", and "how to use python dictionaries".

What are common mistakes with python dictionaries?

Common python dictionaries mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python dictionaries?

Python Dictionaries is used in real Python work. Learning python dictionaries helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Dictionaries free to learn online?

Yes. You can learn python dictionaries free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.