Python Design Patterns Dictionary
Python Design Patterns: Dictionaries
A dictionary is a data structure that consists of a key-value pair. These are widely used as an alternative to JSON – JavaScript Object Notation. Dictionaries are used in API (Application Programming Interface) programming. A dictionary maps one set of objects to another set of objects. Dictionaries are mutable; this means they can be changed as needed.
How to Implement a Dictionary in Python
The following program shows the basic implementation of a dictionary in Python, from its creation to its implementation.
# Create a new dictionary
d = dict() # or d = {}
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345
# print the whole dictionary
print(d)
# print only the keys
print(d.keys())
# print only values
print(d.values())
# iterate over dictionary
for i in d :
print("%s %d" %(i, d[i]))
# another method of iteration
for index, value in enumerate(d):
print (index, value, d[value])
# check if key exist 23. Python Data Structure –print('xyz' in d)
# delete the key-value pair
del d['xyz']
# check again
print("xyz" in d)
Output
The above program produces the following output –
Note – Implementing dictionaries in Python has some drawbacks.
Disadvantages
Dictionaries do not support sequence operations on sequence data types, such as strings, primitives, and lists. These are built-in mapping types.