Python Dictionaries

Creating Dictionaries

The primary way to create a dictionary is by using curly braces {} and specifying key-value pairs within them:

# Example dictionary
my_dictionary = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

In this example:

  • my_dictionary is the variable name assigned to the dictionary.
  • Each line within the curly braces represents a key-value pair separated by a colon :.
  • name, age, and city are the keys (unique identifiers).
  • "Alice", 30, and "New York" are the values associated with the respective keys.

Empty dictionary

To create an empty dictionary, simply use curly braces with nothing inside:

empty_dict = {}

This empty_dict is ready to hold key-value pairs whenever you need them.


Creating dictionaries from other data structures

Python also provides ways to construct dictionaries from existing data structures like lists and tuples:

1. From list of key-value pairs:

You can create a dictionary by providing a list of key-value pairs (tuples) enclosed in square brackets [] inside the curly braces:

my_list = [("name", "Bob"), ("age", 25)]
my_dict = dict(my_list)  # dict() function to convert list to dictionary

Here, my_list contains tuples where the first element is the key and the second element is the value. The dict() function takes this list and constructs a dictionary from it.

2. From list of keys with default value:

You can create a dictionary with a default value for all keys by combining a list of keys with the dict.fromkeys() method:

keys = ["name", "age", "city"]
default_value = "Unknown"
my_dict = dict.fromkeys(keys, default_value)

This creates a dictionary my_dict with keys from keys and assigns the default_value to each key.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What is the primary way to create a dictionary in Python?

Using angle brackets <>
Using square brackets []
Using curly braces {}
Using parentheses ()
Check Answer

How do you create an empty dictionary in Python?

empty_dict = {}
empty_dict = []
empty_dict = ()
empty_dict = dict()
Check Answer

How can you create a dictionary from a list of key-value pairs?

Directly assigning values to keys
Using the dict() function with a list of keys
Using a for loop to assign values
Using the dict() function with a list of tuples
Check Answer

How can you create a dictionary with default values for all keys?

Using dict() with keyword arguments
Using a list comprehension
Using a for loop to iterate
Using dict.fromkeys()
Check Answer

What will my_dict["name"] return if my_dict = {"name": "Alice"}?

KeyError
None
"Alice"
"name"
Check Answer