Dictionaries in Python
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.
The data is stored in key:value pairs in dictionaries, which makes it easier to find values.
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’.
# Example create dictionary using { }
d2 = {1: ‘Chennai', 2: ‘Mumbai', 3: ‘Delhi'}
print(d2)
# Example create dictionary using dict() constructor
d3 = dict(a = “ball", b = “bat", c = “cricket")
print(d3)
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.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square brackets or get() method.
# example
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }
# Example Access using key
print(d["name"]) # output – “Alice”
# Example Access using get()
print(d.get("name") # output – “Alice”
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
# Example Adding a new key-value pair
d["age"] = 22
Print (d)
# Example Updating an existing value
d1[5] = “Success"
print(d1)
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
#Example- Using del to remove an item
del d2[“2"]
print(d2)
d2[“4"] = Kolkata # I want to add an key:value
print(d2)
# Example Using pop() to remove an item and return the value
val = d1.pop(4)
print(val)
# Example Using popitem to removes and returns the last key-value pair.
key, val = d1.popitem()
print("Key: “, {key}, “Value:”, {val})
Nested Dictionaries
d = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(d) # output {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}