USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Dictionaries (Key-Value Pairs)

Lesson 15/35 | Study Time: 45 Min

In real life, a dictionary maps a word to its meaning. Python dictionaries work the same way — they map a key to a value.

Instead of accessing data by position like lists, you access it by a meaningful label. This makes dictionaries incredibly efficient for storing and retrieving structured data.

They are widely used in AI for handling datasets, model configurations, storing labels, and managing structured records.

Creating a Dictionary

Dictionaries are defined using curly braces {}, with each entry written as key: value, separated by commas.

Keys must be unique and immutable (strings, numbers, or tuples). Values can be anything — numbers, strings, lists, or even another dictionary.

Accessing Values

You retrieve a value by referencing its key. There are two ways to do this:

Tip: Use .get() when you are not sure if the key exists, it avoids a KeyError by returning None or a default value instead.

Modifying a Dictionary

Dictionaries are mutable, you can add, update, or remove entries freely.


Common Dictionary Methods


Examples:

Checking Keys and Membership


Iterating Over a Dictionary

You can loop through keys, values, or both using .items().


Nested Dictionaries

A dictionary can contain another dictionary as a value. This is useful for representing complex, structured data.


Nested dictionaries are common in AI when handling JSON data from APIs or storing multi-field records.

Dictionary Comprehension

Similar to list comprehension, dictionaries can be built in a single concise line.



Real-World Use Cases in AI

Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.