Definition and Creating Dictionaries
Dictionary is a data structure that stores key-value pairs. Think of it like a language dictionary where each word (key) has a meaning (value) associated with it.
Ways to Create Dictionaries
Python provides several ways to create dictionaries, from empty ones to those already containing data.
# Creating empty dictionaries
a = {}
b = dict()
print("Empty dictionary a:", a)
print("Empty dictionary b:", b)
# Output: Empty dictionary a: {}
# Output: Empty dictionary b: {}
# Creating dictionary with data
phone = {'ann': 110, 'bob': 991, 'cat': 112, 'dan': 999}
print("Dictionary phone:", phone)
# Output: Dictionary phone: {'ann': 110, 'bob': 991, 'cat': 112, 'dan': 999}
# Creating nested dictionary
person = {1: {'name': 'ann', 'age': 23}, 2: {'name': 'bob', 'age': 21}}
print("Nested dictionary:", person)
# Output: Nested dictionary: {1: {'name': 'ann', 'age': 23}, 2: {'name': 'bob', 'age': 21}}
# Creating dictionary with constructor
month = dict([(1, 'Jan'), (2, 'Feb'), (3, 'Mar')])
mass = dict(Mercury=3.3e23, Venus=4.9e24, Earth=6.0e24)
print("Dictionary month:", month)
print("Dictionary mass:", mass)
# Output: Dictionary month: {1: 'Jan', 2: 'Feb', 3: 'Mar'}
# Output: Dictionary mass: {'Mercury': 3.3e23, 'Venus': 4.9e24, 'Earth': 6.0e24}