The four data types in Python are List, Tuple, Dictionaries, and Set. On this page, we’ll be discussing the Python Dictionary. However, for a clear understanding of the other three, refer to Python Data Types. ln python, it’s frequent that you store your well-organized data under a keyword while Coding.
In this interaction, you’ll be learning in simple and clear terms:
- What is the Python Dictionary?
- Types of the Python dictionary
- Characteristics of the Python
Dictionary
- Creating a python Dictionary
- Operations on python Dictionary
- Built-in functions
Finally, you’ll be free to manifest the knowledge through practice
What is a Python Dictionary?
Simply stated, a Python Dictionary is the collection of ordered items within curly brackets {}, a key: Values. It is used to store values in key:value pairs.
The python Dictionary can be invoked by writing the keyword( that is the word that represents the content value). For the knowledge, the Python Dictionary became an ordered collection from python 3.7 anything backward was not ordered.
Example of a python dictionary
Vehicles = {"Land": "Taxi", "Bicycle": "Motorcycle", "Train": "Bus"}
The python dictionary as a data type has features that you should take cognizance
Characteristics of the Python Dictionary
- Dictionaries keywords are ordered
- Key Values are mutable but keywords must be immutable and the dictionary does not allow duplicates
- Python Dictionaries are within Curly brackets{}
- Python Dictionary is case sensitive, Man and man are taken as different value
- Python Dictionary Values can be of any data type and can repeat
The above are some major characters of the Python dictionary. We’ll be seeing some examples in correspondence to its characters. Before then, let’s Open a Dictionary
Creating a python Dictionary
Before you have access to other operations of the python dictionary, you must create a dictionary first. Good thing is, you can create a dictionary with the dict() function.
Example 1: Creating a dictionary with the dict() function
Python Input:
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'pen', 2: 'pencils'} # dictionary with mixed keys my_dict = {'name': 'Tanya', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'pen', 2:'pencils'}) # from sequence having each item as a pair my_dict = dict([(1, 'pen'), (2,' pencils')])
At this point, you’re set for the journey ahead, Let’s Python up!
Accessing Dictionary Elements in Python
Elements in Python Dictionary can be accessed using two methods which are:
- Square brace [ ]. This raises KeyError when a key is found in the dictionary
- get() function: It gives a non. return of the key is not found
Example:
Python Input:
# get vs [ ] for retrieving elements my_dict = {'Vehicle': 'car', 'bicycle': plane}
# Output: Jack
print(my_dict['vehicle']) # Output: 26
print(my_dict.get('plane')) # Trying to access keys that don't exist throws an error # Output None
print(my_dict.get('jet')) # KeyError
print(my_dict['jet'])
Output: Car plane None
Traceback (most recent call last): File "<string>", line 15, in <module> print(my_dict['jet']) KeyError: 'jet'
The statement above agrees with the box bracket [] and the get() function Methods
Modifying the Python Dictionaries
You can add new items to the python dictionary or change an existing value to another by using the assign function (=). In doing this, if the key is available, the existing value gets updated. If the key isn’t available, a new key: value is added to the dictionary.
Example:
Python Input:
#!/usr/bin/python3 dict = {'Land': 'Train', 'Water': Ship, 'Sky': 'Plane'} dict['Land'] = Train; # update existing entry dict['Space'] = "Spaceship" # Add a new entry print ("dict['Land']: ", dict['Land']) print ("dict['Space']: ", dict['Space'])
Output:
dict['Land']: Train dict['Space']: Spaceship
Carefully study the results above. However, there are more reasons ahead. You shouldn’t stop smelling roses here.
Deleting Python Dictionary
There’s a provision for item deletion in Python. You can either remove an isolated item from the dictionary using the pop() function or you can remove a key:value pair item from the dictionary.
In some cases where necessary, you can get rid of the entire item by consulting the clear() function. However, when things get serious, and you want to get rid of items meticulously, you can use the del keywords to remove individual items or get rid of the entire Dictionary at once.
Example:
Python Input:
# Removing elements from a dictionary # create a dictionary triangle = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove a particular item, returns its value # Output: triangle print(triangle. pop(4)) # Output: {1: 1, 2: 4, 3: 9, 5: 25} print(triangle) # remove an arbitrary item, return (key, value) # Output: (5, 25) print(triangle. pop item()) # Output: {1: 1, 2: 4, 3: 9} print(triangle) # remove all items triangle.clear() # Output: {} print(triangle) # delete the dictionary itself del triangle # Throws Error print(triangle) Output: 16 {1: 1, 2: 4, 3: 9, 5: 25} (5, 25) {1: 1, 2: 4, 3: 9} {} Traceback (most recent call last): File "<string>", line 30, in <module> print(triangle) NameError: name 'triangle' is not defined
Python Dictionary: Methods and Description
The table below carries the methods involved in Python Dictionaries.
Methods | Meaning |
clear() | Removes all data from the dictionary. |
copy() | Gives a shallow copy of the dictionary. |
from keys() | Outputs a new dictionary with keys from seq and value that equals |
get() | Returns the value of the key. If the key is not available, returns to the default |
items() | Return a new list of direct object pairs. |
keys() | Returns new keys to the dictionary |
pop() | Remove the item with the key and give its value or d if the key is available. If d is not available and the key is not found, it returns KeyError. |
pop item() | Removes and returns a key, value, it will raise KeyError if the dictionary is empty. |
set default() | If the key is in the dictionary, it returns a corresponding value. Otherwise, it inserts the key with the value of dan as the output |
update () | Adds dictionary key: value pairs to an existing dictionary |
values() | Gives out a new list of dictionary Values |
Python Dictionary Built-in Functions
Function | Description |
all() | Returns The key: value dictionary from others, overwriting existing keys. |
any() | Returns True if any key of the dictionary is true. Return False. for an empty dictionary |
Len() | Gives the number of Characters in the dictionary |
CMP() | Compares items of two dictionaries. (Not available in Python 3) |
sorted() | Sorts put a new list of keys in the dictionary. |
Summary
Python Dictionary is the collection of ordered items within curly brackets {}, and it has a key: Values. It is used to store values in key:value pairs.
For the knowledge, the Python Dictionary became an ordered collection from python 3.7 anything backward was not ordered.
The Python Dictionaries has characters such as:
- Dictionaries keys are ordered
- Key Values are mutable but keywords must be immutable and the dictionary does not allow duplicates
- Python Dictionaries are within Curly brackets{}
- Python Dictionary is case sensitive, Man and man are tested as different value
- Python Dictionary Values can be of any data type and can repeat
Before you have access to other operations of the Python dictionary you must create a dictionary first.
In this chapter you learned:
- What is the python Dictionary
- Types of the Python dictionary
- Characteristics of the python
Dictionary
- Creating a python Dictionary
- Operations on python Dictionary
- Built-in functions
Now it’s on you to fan to flame what you just learn, for a head start, refer to the python tutorial. Good luck Coding!