What is a Dictionary?
A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are mutable,
unordered collections with elements in the form of a key: value pairs that associate keys to
values. Keys must be unique and immutable (like strings, numbers, or tuples), while values can
be of any data type. Dictionaries are defined using curly braces {} with key-value pairs separated
by colons :.
Basic Syntax
A dictionary is created using curly braces {} with key-value pairs separated by colons :.
Here's the basic syntax:
my_dict = {key1: value1, key2: value2, key3: value3, ...}
key1, key2, key3, etc. are the keys of the dictionary. Keys must be unique and immutable (like
strings, numbers, or tuples).
value1, value2, value3, etc. are the values associated with the keys. Values can be of any data
type. Example
[1]
0s
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
print(student)
{'name': 'Alice', 'age': 20, 'major': 'Computer Science'}
In this example:
"name", "age", and "major" are the keys. "Alice", 20, and "Computer Science" are the values.
Important Considerations
Keys must be unique within a dictionary. If you try to use the same key for multiple entries, the
last value will overwrite the previous one. Keys must be immutable. This means you can't use
mutable objects like lists as keys. Values can be of any data type, including other dictionaries,
lists, or tuples.
keyboard_arrow_down
characteristics of a dictionary in Python:
1. Mutable: Dictionaries are mutable, which means you can change their contents (add,
update, or delete key-value pairs) after they are created.
2. Unordered: Dictionaries are unordered collections, meaning the elements are not stored in
any specific order. You cannot access elements by their index (like you would with lists).
3. Key-Value Pairs: Dictionaries store data in key-value pairs. Each key is unique and
associated with a value.
4. Keys Must Be Immutable: Dictionary keys must be immutable data types like strings,
numbers, or tuples. This is because the keys are used for hashing, which requires them to
be unchanging.
5. Values Can Be Any Type: Values in a dictionary can be of any data type, including other
dictionaries, lists, or tuples. This flexibility allows you to store complex data structures.
6. Defined with Curly Braces: Dictionaries are created using curly braces {} with key-value
pairs separated by colons :.
7. Keys must be unique: Each key within a dictionary must be unique.
8. Indexed by keys: Dictionaries are unordered but they are indexed by keys, and we can
access them by keys.
Creating a Dictionary
[2]
0s
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
print(my_dict)
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Accessing Values
You can access values using their corresponding keys:
[3]
0s
name = my_dict["name"] # Accessing the value associated with the key "name"
print(name) # Output: Alice
Alice
keyboard_arrow_down
Common Operations
Here are some common operations you can perform on dictionaries:
Adding or Updating Items:
[4]
0s
my_dict["occupation"] = "Engineer" # Adding a new key-value pair
my_dict["age"] = 31 # Updating the value of an existing key
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
{'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
Removing Items:
[5]
0s
del my_dict["city"] # Removing a key-value pair using the del keyword
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'}
{'name': 'Alice', 'age': 31, 'occupation': 'Engineer'}
Checking for Keys:
[6]
0s
if "name" in my_dict:
print("Name is present in the dictionary")
Name is present in the dictionary
Getting All Keys or Values:
[7]
0s
keys = my_dict.keys() # Getting all keys as a list-like object
values = my_dict.values() # Getting all values as a list-like object
print(keys) # Output: dict_keys(['name', 'age', 'occupation'])
print(values) # Output: dict_values(['Alice', 31, 'Engineer'])
dict_keys(['name', 'age', 'occupation'])
dict_values(['Alice', 31, 'Engineer'])
Traversing a dictionary / Iterating Through a Dictionary:
[8]
0s
for key, value in my_dict.items(): # Iterating through key-value pairs
print(key, ":", value)
name : Alice
age : 31
occupation : Engineer
len(dictionary)
Returns the number of key-value pairs in the dictionary.
[9]
0s
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
length = len(my_dict) # length will be 3
print(length)
3
dictionary.clear()
Removes all items from the dictionary, making it empty.
[10]
0s
my_dict.clear() # my_dict will become {}
print(my_dict)
{}
dictionary.get(key, default=None)
Returns the value associated with the given key. If the key is not found, it returns the default
value (which is None by default).
[11]
0s
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
name = my_dict.get("name") # name will be "Alice"
print(name)
age = my_dict.get("age") # age will be 30
print(age)
city = my_dict.get("country", "Unknown") # city will be "Unknown" (key "country" not found)
print(city)
Alice
30
Unknown
dictionary.items()
Returns a view object containing all key-value pairs as tuples.
[12]
0s
items = my_dict.items() # items will be a view object
print(items)
for key, value in items:
print(key, ":", value)
dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])
name : Alice
age : 30
city : New York
dictionary.keys()
Returns a view object containing all keys in the dictionary.
[13]
0s
keys = my_dict.keys() # keys will be a view object
for key in keys:
print(key)
name
age
city
dictionary.values()
Returns a view object containing all values in the dictionary.
[14]
0s
values = my_dict.values() # values will be a view object
for value in values:
print(value)
Alice
30
New York
dictionary.update(other_dictionary)
Updates the dictionary with key-value pairs from another dictionary or iterable.
[15]
0s
other_dict = {"occupation": "Engineer", "city": "London"}
my_dict.update(other_dict) # my_dict will be updated with items from other_dict
print(my_dict)
{'name': 'Alice', 'age': 30, 'city': 'London', 'occupation': 'Engineer'}
dictionary.pop(key, default=None)
Removes and returns the value associated with the given key. If the key is not found, it returns
the default value (which is None by default). If default is not specified and the key is not found, a
KeyError is raised.
[16]
0s
age = my_dict.pop("age") # age will be 30, and "age" will be removed from my_dict
city = my_dict.pop("country", "Unknown") # city will be "Unknown" (key "country" not found)
print(age)
print(city)
print(my_dict)
30
Unknown
{'name': 'Alice', 'city': 'London', 'occupation': 'Engineer'}
checking for a key in dictionary:
Method 1: Using the in keyword
<key> in <dictionary> - This will return True in case the given key is present in the dictionary otherwise False.
<key> not in <dictionary> - This will return True in case the given key is not present in the dictionary
otherwise False.
[17]
0s
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
if "name" in my_dict:
print("Key 'name' is present in the dictionary")
else:
print("Key 'name' is not present in the dictionary")
Key 'name' is present in the dictionary
Reasoning:
1. The in keyword checks if the specified key exists as a key in the dictionary.
2. If the key is found, it returns True, and the code inside the if block is executed.
3. If the key is not found, it returns False, and the code inside the else block (if present) is
executed.
Method 2: Using the get() method and checking for None.
This method is safer if you're not sure if the key exists and want to avoid a KeyError if the key is
not found.
[18]
0s
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
value = my_dict.get("country")
if value is not None:
print("country is present in the dict")
else:
print("country is not present in the dict")
country is not present in the dict
Reasoning
1. my_dict.get("country") returns the value if the key "country" exists, otherwise None.
2. if value is not None: checks if the returned value is not None, signifying the key is
present.
3. print("Key 'country' is present in the dictionary") is executed only if the key is found and
value is not None.
keyboard_arrow_down
Programs
1. Write a program to create a dictionary containing names of competition winner students
as key and number of their wins as values. Take 3 inputs for names and wins.
Example:
Enter the name of the winner: Alice
Enter the number of wins: 2
Enter the name of the winner: Bob
Enter the number of wins: 3
Enter the name of the winner: Charlie
Enter the number of wins: 1
OUTPUT:
{'Alice': 2, 'Bob': 3, 'Charlie': 1}