This code demonstrates various methods for creating dictionaries in Python, including literal creation, using the dict() constructor, and building from key-value pairs.
# dictionary_creation.py
# --- Method 1: Using curly braces {} (Dictionary Literal) ---
# This is the most common and straightforward way to create a dictionary.
# Dictionaries store data in key-value pairs.
# Keys must be unique and immutable (e.g., strings, numbers, tuples).
# Values can be of any data type and can be duplicated.
# Example 1.1: Empty dictionary
empty_dict = {}
print('1.1 Empty dictionary:', empty_dict)
# Example 1.2: Dictionary with initial key-value pairs
fruit_prices = {
'apple': 1.00,
'banana': 0.50,
'orange': 1.25
}
print('1.2 Fruit prices dictionary:', fruit_prices)
# --- Method 2: Using the dict() constructor ---
# The dict() constructor can be used in several ways to create dictionaries.
# Example 2.1: From an iterable of key-value pairs (e.g., a list of tuples)
# Each tuple should contain exactly two elements: (key, value)
items_list = [('name', 'Alice'), ('age', 30), ('city', 'New York')]
person_dict = dict(items_list)
print('2.1 Person dictionary (from list of tuples):', person_dict)
# Example 2.2: From keyword arguments (keys must be valid identifiers - strings without spaces/special chars)
# This is convenient when keys are simple string literals.
student_grades = dict(math=95, science=88, history=79)
print('2.2 Student grades dictionary (from keyword arguments):', student_grades)
# Example 2.3: Creating an empty dictionary using dict()
another_empty_dict = dict()
print('2.3 Another empty dictionary (using dict()):', another_empty_dict)
# --- Method 3: Using a dictionary comprehension ---
# Similar to list comprehensions, dictionary comprehensions provide a concise way
# to create dictionaries from other iterables.
# Example 3.1: Creating a dictionary where keys are numbers and values are their squares
squares_dict = {x: x*x for x in range(1, 6)}
print('3.1 Squares dictionary (comprehension):', squares_dict)
# Example 3.2: Creating a dictionary from two lists (keys and values)
keys = ['a', 'b', 'c']
values = [1, 2, 3]
zipped_dict = {k: v for k, v in zip(keys, values)}
print('3.2 Zipped dictionary (comprehension with zip):', zipped_dict)
# --- Dictionary Operations (Brief Overview) ---
# Accessing values
print('\nAccessing values:')
print('Price of apple:', fruit_prices['apple'])
# Adding/Modifying elements
fruit_prices['grape'] = 2.50
fruit_prices['apple'] = 1.10 # Modify existing key
print('Updated fruit prices:', fruit_prices)
# Deleting elements
del fruit_prices['banana']
print('Fruit prices after deleting banana:', fruit_prices)
# Checking if a key exists
print('Is 'apple' in fruit_prices?', 'apple' in fruit_prices)
print('Is 'pear' in fruit_prices?', 'pear' in fruit_prices)