Working with Dictionaries
Dictionary can store data like lists but instead of using only numbers to get the data, you can use almost anything. A dictionary has a concept of a key, with the help of key you are able to access the data. Thus, you can refer to the dictionary as a database for storing and organizing data. Dictionary data can be accessed using keys. The key makes sense because data stored in the dictionary is stored in the form of pairs. Where each pair containing two information Key: Value
If keys are used as a number from 0 to n-1 for n pairs. Then, value accessed using keys is similar to value accessed in the list using indexing.
Example:
sample_dictionary_data = { 0: “pink”, 1: “red”}
While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. A dictionary associates one thing to another, no matter what it is. In this post, we will learn how to create a dictionary & store data using a dictionary. How to access elements from a dictionary, change or add elements in a dictionary, delete or remove elements from a dictionary. Traversing a dictionary, using methods with a dictionary. You will also learn about Dictionary Comprehension, Dictionary Membership Test, Built-in Functions with Dictionary.
Creating a dictionary
In the below code, we will demonstrate, how to create or initialize a dictionary. You will also learn the built-in function dict(), which is used to create a dictionary.
Code:
# empty dictionary
sample_dict = {}
print(sample_dict)
# dictionary with integer keys
sample_dict = {1: 'pink', 2: 'red'}
print(sample_dict)
# dictionary with mixed keys
sample_dict = {'name': 'Pythonbaba', "Role": ["Programmer", "Teacher", "Writer"]}
print(sample_dict)
# using dict()
sample_dict = dict({"color1": 'pink', "color2": 'red'})
print(sample_dict)
# from sequence having each item as a pair
sample_dict = dict([("color1", 'pink'), ("color2", 'red')])
print(sample_dict)
Output:
{}
{1: 'pink', 2: 'red'}
{'name': 'Pythonbaba', 'Role': ['Programmer', 'Teacher', 'Writer']}
{'color1': 'pink', 'color2': 'red'}
{'color1': 'pink', 'color2': 'red'}
Access element using Key
You can normally access Dictionary value using indexing as we have done with lists and tuples. You can also use a key placed in quotes inside square brackets or get() method and retrieve the value linked with a key.
Code:
#When Keys are used as integers
#You can access Dictionary value using indexing
sample_dict = {0: 'pink', 1: 'red'}
print(sample_dict)
print(sample_dict[0])
print(sample_dict[1])
print(sample_dict.get(0))
print(sample_dict.get(1))
sample_dict = {'name': 'Pythonbaba', "Role": ["Programmer", "Teacher", "Writer"]}
print(sample_dict)
print(sample_dict["name"])
print(sample_dict.get("name"))
print(sample_dict["Role"])
print(sample_dict["Role"][0])
print(sample_dict.get(["Role"][0]))
print(sample_dict["Role"][1])
print(sample_dict["Role"][0:1])
print(sample_dict["Role"][1:2])
print(sample_dict["Role"][0:2])
print(sample_dict["Role"][:])
Output:
{0: 'pink', 1: 'red'}
pink
red
pink
red
{'name': 'Pythonbaba', 'Role': ['Programmer', 'Teacher', 'Writer']}
Pythonbaba
Pythonbaba
['Programmer', 'Teacher', 'Writer']
Programmer
['Programmer', 'Teacher', 'Writer']
Teacher
['Programmer']
['Teacher']
['Programmer', 'Teacher']
['Programmer', 'Teacher', 'Writer']
Traversing a Dictionary
Testing if a key is present in the dictionary or not using Membership operators in and not in. Membership operators are only used for keys and not for testing values.
Code:
sample = {"color1": 'pink', "color2": 'red', "color3": 'green', "color4": 'blue'}
cube_values = {a: a* a * a for a in range(5)}
print(cube_values)
for i in cube_values:
print(i, ":", cube_values[i])
print(sample)
for i in sample:
print(i, ":", sample[i])
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
0 : 0
1 : 1
2 : 8
3 : 27
4 : 64
{'color1': 'pink', 'color2': 'red', 'color3': 'green', 'color4': 'blue'}
color1 : pink
color2 : red
color3 : green
color4 : blue
Change or add elements in a dictionary
Dictionary is mutable. We can add new items or change the value of existing items using an assignment operator.
If the key is already present, the value gets updated, else a new key: value pair is added to the dictionary.
Code:
sample_dict = {0: 'pink', 1: 'red'}
print(sample_dict)
sample_dict[1] = "Navy Blue"
sample_dict["color2"] = "Saffron"
sample_dict["3"] = "Green"
print(sample_dict)
Output:
{0: 'pink', 1: 'red'}
{0: 'pink', 1: 'Navy Blue', 'color2': 'Saffron', '3': 'Green'}
Delete or remove elements from a dictionary
We can remove a particular item in a dictionary by using the method pop(). This method removes an item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
Code:
sample = {1: 'pink', 2: 'red', 3: 'green', 4: 'blue', 5: 'saffron' }
print(sample)
# remove a particular item
print(sample.pop(4))
print(sample)
# remove an arbitrary item
print(sample.popitem())
print(sample)
# delete a particular item
del sample[1]
print(sample)
# remove all items
sample.clear()
print(sample)
# delete the dictionary itself
del sample
Output:
{1: 'pink', 2: 'red', 3: 'green', 4: 'blue', 5: 'saffron'}
blue
{1: 'pink', 2: 'red', 3: 'green', 5: 'saffron'}
(5, 'saffron')
{1: 'pink', 2: 'red', 3: 'green'}
{2: 'red', 3: 'green'}
{}
Using methods with Dictionaries
| Name of the method | Usage |
|---|---|
| clear() | Remove all items form the dictionary. |
| copy() | Return a shallow copy of the dictionary. |
| fromkeys(seq[, v]) | Return a new dictionary with keys from seq and value equal to v (defaults to None). |
| get(key[,d]) | Return the value of key. If key doesnot exit, return d (defaults to None). |
| items() | Return a new view of the dictionary's items (key, value). |
| keys() | Return a new view of the dictionary's keys. |
| pop(key[,d]) | Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. |
| popitem() | Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. |
| setdefault(key[,d]) | If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). |
| update([other]) | Update the dictionary with the key/value pairs from other, overwriting existing keys. |
| values() | Return a new view of the dictionary's values |
Dictionary Comprehension
Dictionary comprehension is the easiest way to create a dictionary using an expression. An expression that contains pair (key: value) followed by for statement inside curly braces {}.
Code:
cube_values = {a: a*a*a for a in range(5)}
print(cube_values)
#The above code is similar to
# cube_values = {}
# for a in range(5):
# cube_values[a] = a*a*a
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
Dictionary Membership Test
Testing if a key is present in the dictionary or not using Membership operators in and not in. Membership operators are only used for keys and not for testing values.
Code:
cube_values = {a: a*a*a for a in range(5)}
print(cube_values)
print(2 in cube_values)
print(4 in cube_values)
print(27 in cube_values)
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
True
True
False
Built-in Functions used with Dictionary
We will discuss the following functions:
| Name of Function | Usage |
|---|---|
| all() | Return True if all keys of the dictionary are true (or if the dictionary is empty). |
| any() | Return True if any key of the dictionary is true. If the dictionary is empty, return False. |
| len() | Return the length (the number of items) in the dictionary. |
| sorted() | Return a new sorted list of keys in the dictionary. |
Code:
sample = {4: 'pink', 3: 'red', 1: 'green', 2: 'blue'}
cube_values = {a: a*a*a for a in range(5)}
cube_2 = cube_values
print(cube_values)
print(all(cube_values))
print(any(cube_values))
print(len(cube_values))
print(sorted(sample))
Output:
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64}
False
True
5
[1, 2, 3, 4]
{4: 'pink', 3: 'red', 1: 'green', 2: 'blue'}