Ad space (banner)
🐍Python Lessons
Lesson 7 / 69

Working with Dictionaries (dict)

This lesson covers the basics of using dictionaries (dict) in Python, so you can group related information together. It's written for anyone searching "Python dictionary tutorial" or "Python dict for beginners".

A dictionary (dict) stores data as "key: value" pairs — similar in spirit to a JavaScript object. It's well suited to grouping related information, like a person's profile. If a list represents "a row of same-kind data," a dictionary is better suited to representing "one bundle of information for one thing."

The sample code gives a dictionary called user three keys — name, age, and hobby — and retrieves values with square brackets, like user["name"]. Notice that the number is converted with str() before being concatenated, since joining a number directly to a string would raise a TypeError.

A common beginner mistake is accessing a key that doesn't exist, which raises a KeyError and halts execution. When you're not sure a key exists, the .get() method (covered in a later lesson) lets you retrieve a value safely without an error. Confusing dictionaries with lists and trying to access them by number is another frequent slip.

In real web applications, most user information is passed around in exactly this dict shape. JSON data returned from an API maps directly onto Python dictionaries, so becoming comfortable with dicts is genuinely foundational to web development.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)