my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}
my_dict
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
You can access values in a dictionary using their keys:
print(my_dict["key1"])
value1
states = {} # Create empty dict
states['ca'] = 'California' # 1. Set key/value pairs into dict
states['ok'] = 'Oklahoma'
states['nj'] = 'New Jersey'
states['tx'] = 'Texas'
states
{'ca': 'California', 'ok': 'Oklahoma', 'nj': 'New Jersey', 'tx': 'Texas'}
type(states)
dict
Source: Nick Parlante's Python guide
phonebook = {"Alice": "555-1234", "Bob": "555-5678", "Charlie": "555-9012"}
phonebook
{'Alice': '555-1234', 'Bob': '555-5678', 'Charlie': '555-9012'}
print(phonebook["Alice"])
555-1234
print(phonebook.keys())
dict_keys(['Alice', 'Bob', 'Charlie'])
print(phonebook.values())
dict_values(['555-1234', '555-5678', '555-9012'])
print(phonebook.items())
dict_items([('Alice', '555-1234'), ('Bob', '555-5678'), ('Charlie', '555-9012')])
phonebook["John"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[12], line 1 ----> 1 phonebook["John"] KeyError: 'John'
my_tuple = ("value1", "value2", "value3")
my_tuple
You can access values in a tuple using their index:
print(my_tuple[0])
days_of_week = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
days_of_week
print(days_of_week[0])
print(days_of_week.count("Monday"))
print(days_of_week.index("Wednesday"))
Storing information about a person, such as their name, address, and phone number:
person = {"name": "Jane Doe", "address": "123 Main St", "phone": "555-1234"}
person
Storing a dictionary of translations between different languages:
translations = {"hello": {"spanish": "hola", "french": "bonjour"}}
translations
Representing a point in two-dimensional space:
point = (3, 5)
point
Storing the RGB color values for a particular color:
color = (255, 128, 0)
color
Factorial is a mathematical function that is represented by an exclamation mark (!). It is used to find the product of all positive integers from 1 to a given number. For example, the factorial of 5 (represented as 5!) is calculated as 5 x 4 x 3 x 2 x 1, which equals 120. In other words, factorial is the multiplication of all positive integers up to a given number.
Write a program that calculates the factorial of 5.
# Solution: Factorial