Dictionary
Unordered collection of items / elements. Each item has two parts - key : value
A mapping between key and it’s value, separated by colon (:)
Items are enclosed in {} and separated by comma.
We are optimized to retrieve data using key. So key (values) should be unique.
They can be integer, float, string or tuple.
D[key] can be used for accessing element, also to add element in an existing
dictionary.
# Creating an empty Dictionary
D = {}
print("Empty Dictionary: ")
print(D)
# Creating a Dictionary with Integer Keys
Dict = {1: ‘AAA', 2: ‘BBB', 3: ‘CCC'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary with Mixed keys
Dict = {'Name': ‘Govind', 1: [10, 11, 12, 13]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary with dict() method
D=dict({1: 'AAA', 2: 'BBB', 3:'CCC'})
print("\nDictionary with the use of dict(): ")
print(D)
# Adding elements one at a time
Dict={}
Dict[0] = ‘Govind'
Dict[2] = ‘Prasad'
Dict[3] = ‘Arya’
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values to a single Key
Dict['V'] = 1, 2
print("\nDictionary after adding set of values: ")
print(Dict)
# Updating existing Key's Value
Dict[‘V’] = 3,4
print("\nUpdated dictionary: ")
print(Dict)
# Creating a Dictionary
D = {1: ‘Prasad', 'name': ‘Govind', 3: ‘Arya'}
# accessing a element using key
print("Accessing a element using key:")
print(D['name'])
# accessing a element using key
print("Accessing a element using key:")
print(D[1])
# accessing a element using get() method
print("Accessing a element using get:")
print(D.get(3))
D={1:'AAA', 2:'BBB', 3:'CCC'}
print("\n all key names in the dictionary, one by one:")
for i in D:
print(i, end=' ')
print("\n all values in the dictionary, one by one:")
for i in D:
print(D[i], end=' ')
print("\n all keys in the dictionary using keys()method:")
for i in D.keys():
print(i, end=' ')
print("\n all values in the dictionary using values()method:")
for i in D.values():
print(i, end=' ')
print("\n all keys and values in the dictionary using items()method:")
for k, v in D.items():
print(k, v, end=' ')