A Python dictionary
A Python dictionary
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"))
Problems of Dictionary
Length of a Dictionary
Remove minimum elements such that no common elements exist in two arrays