Dictionary Variables in Python
In Python, dictionaries are a special type of data structure that store a collection of objects, each accessible via a unique key. Each key is associated with a value.
variable = { key1: value1, ... , keyN: valueN }
Technically, this is known as an associative array.
What is an associative array?
Each element in the dictionary is a pair consisting of a key and a value, separated by a colon.
The pairs in the list are separated by commas.
Note: A dictionary key can be an integer, a string, or a tuple.
- A Practical Example
- How to Display Dictionary Keys
- How to Add a Key to the Dictionary
- How to Check for a Key's Presence
- How to Retrieve a Key's Value
- How to Remove an Element from the Dictionary
- How to Count the Elements in a Dictionary
- How to Create an Empty Dictionary
- Dictionary Methods
- Dictionary Comprehension
A Practical Example
To create an 'employees' variable, use the dict()
function.
employees = dict()
Then, assign elements and keys to the variable.
employees = { 'Andrea':1182, 'Paolo':1034, 'Mario':1248 }
The dictionary contains the names of some employees and their respective ID numbers.
In the next line, we retrieve the element with the key 1182.
So, if you type
employees['Andrea']
The interpreter fetches the value assigned to the key 'Andrea' in the "employees" dictionary and displays it.
The output will be:
1182
This demonstrates how to use dictionary variables in Python.
An Alternative Way to Create Dictionaries in Python
Python allows you to create a dictionary by spreading the assignment operations across multiple lines.
Dictionary={}
Dictionary['Andrea']=1182
Dictionary['Paolo']=1034
Dictionary['Mario']=1248
The end result is the same.
In this approach, the key-value pairs are assigned on different lines.
This method is particularly useful in loops or when the dictionary contains numerous pairs.
How to Display Dictionary Keys
To list all the keys in the dictionary, use the keys
method:
employees.keys()
The result of this command is:
dict_keys(['Andrea', 'Paolo', 'Mario'])
These are the keys in the employees dictionary.
How to Add a Key to the Dictionary
To add a new key to the dictionary variable, perform an assignment operation.
On the left of the equals sign, specify the variable and the key in square brackets. On the right, specify the value to assign.
variable['key'] = value
A Practical Example
To assign the value 1182 to the key 'Andrea' in the Dictionary variable, write
Dictionary['Andrea'] = 1182
How to Check for a Key's Presence
To check if a key is present in the dictionary, use the in
operator.
'Andrea' in employees
The result is:
true
The key 'Andrea' is indeed present in the employees dictionary.
How to Check for a Key's Absence?
Just add the not
operator.
'Andrea' not in employees
How to Retrieve a Key's Value
To retrieve the value of a dictionary key, type the variable name with the key in square brackets.
dictionary['key']
The interpreter recognizes this as a dictionary and displays the value associated with the key.
A Practical Example
To retrieve the value assigned to the key 'Andrea' in the 'employees' dictionary, write
employees['Andrea']
The output will be:
1182
How to Remove an Element from the Dictionary
To delete an element from the dictionary, use
del employees['Andrea']
This command removes the key 'Andrea' from the employees dictionary.
How to Count the Elements in a Dictionary
To get the number of elements in a dictionary, use the len
function.
len(dictionary_name)
A Practical Example
To get the number of elements in the employees dictionary, type:
len(employees)
The output will be:
3
How to Create an Empty Dictionary
To create an empty dictionary, assign two curly braces { }
to the variable.
dictionary = {}
The interpreter creates a dictionary with no elements inside.
Note: Empty curly braces are an alternative way to declare a dictionary variable. When the interpreter recognizes them, it automatically declares the variable as a dictionary.
Dictionary Methods
Dictionaries in Python come with several useful methods.
The main methods for dictionary variables are:
- s.clear()
Removes all elements from the dictionarys
. - s.copy()
Creates a new dictionary that is a copy ofs
. - s.get(key, default)
Retrieves the value associated withkey
from the dictionary. If the key is not present, it returns thedefault
value. - s.keys()
Displays all the keys of the dictionarys
. - s.items()
Displays all the key-value pairs of the dictionarys
. - s.setdefault(key, default)
Retrieves the value associated withkey
. If the key is not present, it returns thedefault
value and adds the key-value pair to the dictionary. - s.values()
Displays all the values in the dictionarys
.
Dictionary Comprehension
Comprehensions can also be applied to dictionaries.
However, unlike sets, dictionaries require working with key-value pairs.
A Practical Example
provinces = { 'Rome':'RM', 'Milan':'MI' }
abbreviations = { value:key for key, value in provinces.items() }
The above comprehension creates a new 'abbreviations' dictionary by swapping the keys and values of the 'provinces' dictionary.