What is Dictionary in Python
Python has many data structures, and one of them is a dictionary, an unordered, indexed collection of items where items are stored in the form of key-value pairs. And keys are unique, whereas values can be changed; dictionaries are optimized for faster retrieval when the key is known, values can be of any type, but keys are immutable and can only be strings, numbers, or tuples; dictionaries are written inside curly braces.
Table of Content
- What is Dictionary in Python
- Creating a Dictionary
- Accessing Dictionary Elements
- Modifying Dictionary Elements
- Dictionary Methods and Operations
- Common Dictionary Operations and Patterns
- Dictionary Views
- Dictionary Key Restrictions and Best Practices
- Applications and Use Cases of Python Dictionary
- Python Dictionary Functions
- Python Ordered Dictionary
- Python Dictionary Methods
- Examples to Implement in Python Dictionary
Syntax:
{ Key : Value }
Example:
{ 'A':'Apple' ,'B':'Ball','c':'cat','d':'dog','e':'elephant'
'f ':'frog','g':'gel','h':'head','i':'impala','j':'jug' }
As mentioned above, the dictionary is wrapped in curly braces with a key value format. In our above example, ‘A’ is the key, and ‘Apple’ is its value. In this concept, we strictly maintain the primary key, which implies that we cannot assign the equivalent key just once.
Key Highlights
- Dictionary in Python are changeable data structures that help to store key-value pairs. These don’t contain any duplicates, and they are ordered in format.
- Creating the dictionary using the dict() command or curly braces {} is easy. After creating the dictionary, it is easy to add, remove, or manipulate the dictionary.
- The key should be a single element, and the values can be of any kind, from integer, tuple, list, etc.
Creating a Dictionary
In Python, it is easy to create a dictionary, add the items inside the curly braces and assign them to a variable name. The items will be in the form of key: value pairs; you need to separate each item with a comma.
Syntax:
Variable_name = {key:value, key:value, key:value, etc }
Example:
#We will follow this syntax student_marks = {"ID":total_marks}
student_marks = {"20":250, "21":265, "22":278, "23":249, "24":280}
print("\nList of students with total marks obtained:")
print(student_marks)
Output:
Accessing Dictionary Elements
The dictionary keys are distinct; hence, it is easy to access the values using keys. You can print the dictionary values with the help of keys or use the get() method to print the same.
Example #1
Code:
#Access the dictionary with keys
first_dict={1:"Arden",2:"Ella",3:"Alice",4:"Olive"}
print("\nPrinting student names:")
print("1:%s"%first_dict[1])
print("2:%s"%first_dict[2])
print("3:%s"%first_dict[3])
print("4:%s"%first_dict[4])
Output:
Example #2
Code:
#Access the dictionary with get method
first_dict={1:"Arden",2:"Ella",3:"Alice",4:"Olive"}
print(first_dict.get(3))
print(first_dict.get(4))
Output:
Modifying Dictionary Elements
The Python dictionary allows you to modify the elements added to the dictionary with the help of the update() method.
The update process defines two means: adding a new element to an existing dictionary or updating a key-value pair of an existing dictionary. So, when you add a new item, it gets appended to the end of the dictionary. Similarly, when you update an existing dictionary component, there is no positional change; only the update is applied to the affected item. The examples below illustrate these scenarios. The first example adds a new element called Bike#4 with the value “Aprilia” to the dictionary. In the next instance, the existing item, Bike#3, is modified to change the current value “Yamaha” to “KTM” The output snapshot shows that the change is applied only to the corresponding item, and there is no positional change.
Code:
Bikes={'Bike#1':'Ducati','Bike#2':'Cannondale','Bike#3':'Yamaha' }
Bikes.update({'Bike#4' : 'Aprilia'})
print("All Top Bikes in market List1 :\n ", Bikes)
print("!------------------------------------------------!")
Bikes.update( {'Bike#3' : 'KTM'})
print("All Top Bikes in market List2 :\n ", Bikes)
Output:
Dictionary Methods and Operations
1. Adding and Updating Elements
The Python dictionary is mutable; hence, you can use certain keys to add new elements or update the elements that are already present in the list.
Code:
#Adding set of element to dictionary at a time
Dict = {0, 'Hello', 25}
print("\nPredefined dictionary: ")
print(Dict)
New_Dict = {}
New_Dict[0] = 1
New_Dict[1] = 'Kitty'
New_Dict[2] = 21
print("\nNew dictionary after adding elements: ")
print(New_Dict)
Output:
2. Removing Elements
Using pop() and popitem() method
Code:
# dictionary creation
dict_1 = {1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49}
# item deletion
print( " ITEM DELETION ")
print(dict_1.pop(3))
print(" ")
print(" Dictionary after deletion " )
print(dict_1)
print(" ")
print(" Arbitrary item removal " )
# Arbitrary item removal
print(dict_1.popitem())
print(" ")
print(" Dictionary after deletion " )
print(dict_1)
print(" ")
print(" Dictionary after removing all items " )
# remove all items
dict_1.clear()
print(dict_1)
Output:
Explanation: The above example involves the dictionary creation process using an unusual and indexed deletion of the dictionary items. The process of deletion is achieved using the popitem() method. Initially, a pop is implied based on the index; next, an undefined pop is implied, which removes the last element in the dictionary; lastly, the entire dictionary is cleaned up using the clear method.
3. Dictionary Size and Membership
You can measure the length of the dictionary using the len() method. The syntax is simple, use len(dict), and you will see the result with the size.
Code:
Dict = {0, 'Hello', 25}
print("\nPredefined dictionary: ")
print(Dict)
print("\nLength of the Dictionary: ")
print(len(Dict))
Output:
4. Dictionary Iteration
The dictionary iteration is allowed with the help of the for loop. You can use the key(), items(), or values() method to iterate the value in the dictionary.
Using keys() method
Code:
#Iterating dictionary with keys() method
first_dict={1:"Arden",2:"Ella",3:"Alice",4:"Olive"}
for keys in first_dict.keys():
print(keys)
Output:
Using values() method
Code:
#Iterating dictionary with values() method
first_dict={1:"Arden",2:"Ella",3:"Alice",4:"Olive"}
for values in first_dict.values():
print(values)
Output:
Using items() method
Code:
#Iterating dictionary with items() method
first_dict={1:"Arden",2:"Ella",3:"Alice",4:"Olive"}
for keys, values in first_dict.items():
print(keys,values)
Output:
Common Dictionary Operations and Patterns
1. Checking if a Key Exists
The items method displays all the elements (tuples) present in the Python dictionary. So when a dictionary item is applied to an item’s method, all keys and values associated with that respective dictionary will be displayed. In the below example, the dictionary Bikes is applied to the items() method, which shows every bike name and key in the console.
Code:
Bikes={'Bike#1':'Ducati','Bike#2':'Cannondale','Bike#3':'Yamaha' }
print('All Top bikes in the market\n',Bikes.items())
Output:
2. Retrieving Values Safely
The get() method of the dictionary can get any default value without an error if the key does not exist.
Code:
d = {10: '100', 20: '1000', 30: '10000'}
print("\nRetriveing second key: ")
print(d.get(20))
print("\nObtaining the unknown key")
print(d.get(40, "Not found"))# It'll print "Not found" since 4th key is absent
Output:
3. Sorting a Dictionary
The elements of a dictionary can be sorted using the sort() method. This method sorts each element of the dictionary accordingly.
Code:
Bikes={'Bike#1':'Ducati','Bike#2':'Cannondale','Bike#3':'Yamaha' }
Bike_sorted = Bikes.items()
print('All Top bikes in the market\n',Bike_sorted)
Output:
4. Merging Dictionaries
The ** operator helps to merge two dictionaries in Python.
Code:
dict_1 = {0: 100, 1: 200}
dict_2 = {2: 'a', 4: 'b'}
print("\nNew dictionary after merging : ")
print({**dict_1, **dict_2})
Output:
5. Nested Dictionaries
Including one dictionary in another is called the nesting method. The nested dictionaries help to obtain the results that are interlinked with each other.
Code:
my_dict = {'dict_1': {0: 100, 1: 200},
'dict_2': {2: 'a', 4: 'b'}}
print("\nNew dictionary : ")
print(my_dict)
Output:
Dictionary Views
The main view objects of the dictionary in Python are keys, values, and items.
- Dictionary Keys View: The view object keys represent all the keys in a dictionary. Printing the view object keys displays a new list of all the keys in the dictionary in order of insertion. Once we retrieve all the keys using the keys() method into a variable, if we update the dictionary, the changes will be reflected in the variable.
- Dictionary Values View: The values() is a built-in method of the Python programming language that returns a view object. That view object contains the value of the dictionary as a list.
- Dictionary Items View: The items() method returns a new view of the dictionary’s items ((key, value) pairs) as a list with all dictionary keys with values.
Dictionary Key Restrictions and Best Practices
Firstly, the keys in a dictionary can only be used once. If you use it more than once, it simply replaces the value. That is adding duplicate keys to the program.
You cannot use another dictionary and lists as dictionary keys, as these are mutable. So instead, you can use an integer, string, float, or boolean.
Applications and Use Cases of Python Dictionary
A Python dictionary is a fast and versatile way to store and retrieve data using a name or even a more complex object type rather than just an index number.
When you want to create a dictionary that stores the count of each word in the strings.
With a large dictionary, there might come a point where you need to append a single character to all of them.
When a dictionary has unique keys and values and would like to invert the mapping from keys: values to values: keys.
Python Dictionary Functions
The below table shows the functions of the Dictionary in Python:
Method | Description | Syntax |
sort() | Allows sorting the dictionary items | dict.sort() |
len() | Used to determine the total number of items in the dictionary | len(dict) |
all() | It returns true values if each of the dictionary’s keys contains a true Boolean value. | all(dict) |
any() | It returns a true value if one dictionary key does have a Boolean expression of true. | any(dict) |
Here is the explanation with examples:
len()
The len() method determines the count of elements in a given dictionary component. So the overall count of the total number of key-value pairs in the corresponding dictionary will be displayed. Moreover, this acts as a wrapper method so that the dictionary item will be wrapped into the length method.
Code:
Bikes={'Bike#1':'Ducati','Bike#2':'Cannondale','Bike#3':'Yamaha' }
print('Total bikes in the market',len(Bikes))
Output:
str()
The str() method converts a dictionary into a string format. This is more of a typecasting method. So typecasting means the conversion of a component in one data type to a different data type value. Again, this implies a wrapper process where the impacted dictionary component will be wrapped into the str() method. The below example shows clearly that the generated dictionary component has been transmuted into a string component. So this means all the items, corresponding keys, and values will be treated as string components.
Code:
Bikes = {'Bike#1' : 'Bajaj','Bike#2' : 'Hero Honda','Bike#3' : 'Yamaha' }
Bikes_str = str(Bikes)
print(' Bikes datatype format ',type(Bikes_str))
Output:
Python Ordered Dictionary
Orderdict is very similar to standard dictionary data types in Python programming; apart from these, ordered dictionaries are much more efficient for reorganization operations. Here, the sequence of insertion has been very strictly maintained. The most important protocols of the ordered dictionary are as below:
- Inserting an existing key element into an ordered dictionary replaces the existing key with the new key item.
- Deleting and reinserting items in an ordered dictionary implies that the deleted item will be added as a new and last item in the dictionary.
- Algorithmically, OrderedDict has been capable of seizing intermittent reshuffle practice well over again than normal dictionaries.
Python Dictionary Methods
The built-in methods used in Python dictionary is as below:
Functions | Description |
Python Dictionary clear() | Removes all Items |
Python Dictionary copy() | Returns Shallow Copy of a Dictionary |
Python Dictionary from keys() | Creates a dictionary from the given sequence |
Python Dictionary get() | Find the value of a key |
Python Dictionary items() | returns a view of the dictionary’s (key, value) pair |
Python Dictionary keys() | Prints the keys |
Python Dictionary pop item() | Remove the last element of the dictionary |
Python Dictionary set default() | Inserts Key With a Value if Key is not Present |
Python Dictionary pop() | removes and returns elements having given key |
Python Dictionary values() | returns a view of all values in the dictionary |
Python Dictionary update() | Updates the Dictionary |
copy()
The copy method copies one dictionary to another, copying the key-value pairs from one dictionary to another. Using this process in a dictionary with existing contents replaces all the active dictionary pairs with new pairs. The newly declared dictionary item will copy and incorporate all the items as components. In the below example, we could notice that the dictionary Bikes’ components are copied into the newly mentioned variable Vehicles, which gets itself converted into a dictionary because of its assignation.
Code:
Bikes={'Bike#1':'Ducati','Bike#2':'Cannondale','Bike#3':'Yamaha' }
Vehicles = Bikes.copy()
print("All Top Bikes in market : \n", Vehicles)
Output:
Code:
from collections import OrderedDict
Vehicles_ordered_dict=OrderedDict({'Bike1':'yamaha','Bike2':'honda','Bike3':'bajajpito','Bike4':'pulser','Bike5':'apache','Car1':'fiat','Car2':'honda-civic','Car3':'sonato','Car4':'i10','Car5':'i20'})
Vehicles_ordered_dict['Bike6']= 'TVS50'
Vehicles_ordered_dict['Car6']= 'ford'
print(" ")
print(" ALL KEYES IN VEHICLES ")
print('print the keys :', Vehicles_ordered_dict.keys())
print(" ")
print(" ALL VALUES IN VEHICLES ")
print('print the Values :', Vehicles_ordered_dict.values())
Output:
Examples to Implement in Python Dictionary
Below is an example of proper implementation.
Code:
Vehicles = {}
#Variable declaration
Bike_keys=['Bike#1','Bike#2','Bike#3','Bike#4','Bike#5',]
Bike_values = ['Bajajpito','Apache','Enfield','Enfieldclassic','Marlbaro']
Car_keys=['Car#1','Car#2','Car#3','Car#4','Car#5']
Car_values=['Fiat','Baleno','Bentley','Ferrari','Jaguar']
# Casting and Zipping Keys with values
Bikes=dict(zip(Bike_keys, Bike_values))
Cars=dict(zip(Car_keys, Car_values))
Bikes.update(Cars)
Vehicles = Bikes.copy()
#Print Section
print(" ")
print(" BIKES IN THE MARKET ")
print(Bikes)
print(" ")
print(" CARS IN THE MARKET ")
print(Cars)
print(" ")
print(" ALL VEHICLES IN THE MARKET ")
print(Vehicles)
Output:
Explanation: In the above example, creating a dictionary involves using an unusual casting method and merging two entities. The program involves collecting values into two separate lists. The first list acts as the dictionary Bikes’ key items; the second list acts as the dict Bikes’ values. The code repeats the above process for different car keys and value lists, fusing both individual lists into a single dictionary item. The code then proceeds to join these individual dictionaries, which zip from a separate list in successive sections. To accomplish this joining process, it utilizes the update() method. It updates the dictionary by adding it as an item to another dictionary element, creating a brand new dictionary that combines the provided dictionary items below.
Conclusion
Collection data types hold a superior role in all standard programming languages on the market. In such cases, Python’s dictionary component offers a large space for sophisticated data handling in Python. The varied methods in these dictionary items offer many techniques to perform on the data entities.
Frequently Asked Questions (FAQs)
Q1. How to create an empty dictionary in Python?
Ans: Create a variable name that refers to the dictionary name. Now you can assign the empty curly braces to a variable name. It is also possible to use dict() without passing any commands.
For example, variable name = dict(), my_dictionary = dict().
Q2. How to merge two dictionaries in Python?
Ans: There are various methods to merge two dictionaries in Python. You can use the unpacking operator (**), Union operator (|), using for loop, using update() method, using copy() and update() method, using dict() constructor, and using chain() method.
Q3. What is the difference between a list and a dictionary in Python?
Ans: The list in Python is a collection of index value pairs, the same as arrays in C or C++, or Java. In contrast, dictionaries in Python have values in key-value pairs in the hashtable format.
Recommended Articles
We hope that this EDUCBA information on “Dictionary in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.