dict Data TypeA dict (dictionary) variable is a collection of key:value pairs.
These pairs are separated by commas and the sequence is delimited by braces { }.
To establish the correspondence between the elements constituting the key and value pair, we use the symbol : (colon.)
To access the values of a dict variable, we use the brackets [ ].
The value assigned to a key must be non-mutable (number, tuple, string, etc.)
The value assigned to a key must be unique.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
print(data)
print(data['org'])
print(data.keys())
print(data.values())
We add an element to a dict by assigning a value component to a new key component.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
print(data)
# Add an item
data['edu'] = 'Education'
print(data)
The del statement is used to delete an element from a dict.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
print(data)
# Remove an item
del data['net']
print(data)
The pop() method is used to remove and return an element of specified index from a dict.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
print(data)
# Remove an item
element = data.pop('com')
print(data)
print('Popped element:', element)
The clear() method is used to remove all elements from a dict.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
print(data)
# Clear the dictionary
data.clear()
print(data)
The dict data type is mutable in nature.
We change the value component of an element of a dict by referring to its key component.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Networking'
}
print(data)
# Change the value of an item
data['net'] = 'Network'
print(data)
dictA dict is bounded and iterable: we can iterate through the key components of its elements in a for loop.
We use the membership operator in to iterate through the elements of a dict.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
# iterate on dictionary keys one by one
for domain in data :
entity = data[domain]
print(domain, ':', entity)
dictThe length of a dict is the number of elements it contains.
The len() function returns the length of a dict.
Example
data = {
'com' : 'Commercial',
'org' : 'Organization',
'net' : 'Network'
}
# get dictionary length
print(len(data))
dict MethodsThe following are built-in methods for a dict object.
Method
Description
dict.keys()
Returns list of key components of dict.
dict.values()
Returns list of value components of dict.
dict.get()
returns value component for specified key in dict.
dict.update()
Adds key:value pair to dict.
dict.pop()
Removes and returns last element or element with specified key from dict.
dict.clear()
Removes all elements of dict.
dict.copy()
Returns a copy of dict.