A Python dictionary is a data structure that stores the value in key: value pairs.
Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
How to Create a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
//{1: 'Geeks', 2: 'For', 3: 'Geeks'}
# create dictionary using dict() constructor
d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)
//{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
Dictionary keys are case sensitive: the same name but different cases of Key will be
treated distinctly.
Keys must be immutable: This means keys can be strings, numbers, or tuples but not
lists.
Keys must be unique: Duplicate keys are not allowed and any duplicate key will
overwrite the previous value.
Dictionary internally uses Hashing. Hence, operations like search, insert, delete can
be performed in Constant Time.
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }
# Access using key
print(d["name"])
or
# Access using get()
print(d.get("name"))
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Adding a new key-value pair
d["age"] = 22
# Updating an existing value
d[1] = "Python dict"
print(d)
//{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
We can remove items from dictionary using the following methods:
del: Removes an item by key.
pop(): Removes an item by key and returns its value.
clear(): Empties the dictionary.
popitem(): Removes and returns the last key-value pair.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}
# Using del to remove an item
del d["age"]
print(d)
//{1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)
//Geeks
# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")
//Key: 3, Value: Geeks
# Clear all items from the dictionary
d.clear()
print(d)
//{}
Iterating Through a Dictionary
We can iterate over keys [using keys() method] , values [using values() method] or both
[using item() method] with a for loop.
d = {1: 'Geeks', 2: 'For', 'age':22}
# Iterate over keys
for key in d:
print(key)
# Iterate over values
for value in d.values():
print(value)
# Iterate over key-value pairs
for key, value in d.items():
print(f"{key}: {value}")
Example of Nested Dictionary:
d = {1: 'Geeks', 2: 'For',
3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(d)
//{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Problems of Dictionary
Length of a Dictionary
Check if a Key Exists
Access a Value by Key
Remove a Key from a Dictionary
Remove keys with substring values
Sum All Numeric Values in a Dictionary
Find Keys with Maximum Value
Remove Duplicates from a Dictionary
Filter Dictionary by Key Prefix
Count Frequency of Elements Using Dictionary
Check if two arrays are equal or not
Max distance between two occurrences in array
2 Sum – Count Pairs with target sum
3 Sum – Count all triplets with target sum
Count all pairs with absolute difference equal to k
Remove minimum elements such that no common elements exist in two arrays
Check If Array Pair Sums Divisible by k
Longest subarray with sum divisible by K
Longest Subarray having Majority Elements Greater Than K