Introduction to 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 string, numbers or tuples dictionaries are written inside curly braces.
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 within curly braces with a key, value format associated with it. in our above example, ‘ A ‘ acts as the key, and ‘Apple’ is the value associated with it. In this, the concept of the primary key is strictly maintained. that means like additional than just the once the equivalent key cannot be assigned.
Methods in Python Dictionary
Below table shows the methods of the Dictionary in Python:
Method | Description | Syntax |
copy() | Entire dictionary will be copied into a new dictionary | dict.copy() |
update() | Helps to update an existing dictionary item | dict.update(dict2) |
items() | Used for displaying the items of a dictionary | dict.items() |
sort() | allows sorting the dictionary items | dict.sort() |
len() | used to determine the total number of items in the dictionary | len(dict) |
Str() | Make a dictionary into a printable string format | Str(dict) |
Below are the methods given:
1. copy()
To copy one dictionary to another, the copy method is used, So the key-value pairs of one dictionary will be copied to the other one. Using this process to a dictionary with existing contents makes all the active dictionary pairs to be put back with the new pairs. so this all the items will be copied and become a component of the newly declared dictionary item. In the below example, we could notice that the dictionary Bikes’ components are copied into a newly mentioned variable Vehicles, which gets itself converted into a dictionary because of its assignation.
Code:
Bikes = {'Bike#1':'Bajaj','Bike#2':'Hero Honda', 'Bike#3':'Yamaha' }
Vehicles = Bikes.copy()
print("All Top Bikes in market : ", Vehicles)
Output:
2. update()
The process of update defines two means; one is adding a new element to an existing dictionary or updating a key-value pair of an existing dictionary. So when a new item is added, it gets appended to the end of the dictionary. Similarly, when an existing dictionary component is updated the, there will not be any positional change to a component; only the update will be applied for the impacted item. Examples of the same are depicted below. A new element call Bike#4 with the value Yamaha has been added into the dictionary in the below example. In the next instance, the existing item Bike#3 is modified such that the current value of Hero Honda is changed to Hero-Honda. as displayed in the output snap, the change is applied only to the corresponding item, and there doesn’t exist any positional change to it.
Code:
Bikes={'Bike#1':'Bajaj','Bike#2':'Hero Honda','Bike#3':'Yamaha' }
Bikes.update({'Bike#4' : 'Bullet'})
print("All Top Bikes in market List1 : ", Bikes)
print("!------------------------------------------------!")
Bikes.update( {'Bike#3' : 'Hero-Honda'})
print("All Top Bikes in market List2 : ", Bikes)
Output:
3. items()
The items method is used for displaying all the elements (tuples) present in the python dictionary. so when a dictionary item is applied to an items method, all keys and values associated with that respective dictionary will be displayed. In the below example, the dictionary Bikes is applied for items() method, which makes as shown below each and every bike name along with its key has been displayed in the console.
Code:
Bikes={'Bike#1':'Bajaj','Bike#2':'Hero Honda','Bike#3':'Yamaha' }
print('All Top bikes in the market',Bikes.items())
Output:
4. sort()
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':'Bajaj','Bike#2':'Hero Honda','Bike#3':'Yamaha' }
Bike_sorted = Bikes.items()
print('All Top bikes in the market',Bike_sorted)
Output:
5. len()
The len() method is used to determine the count 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 it means the dictionary item will be wrapped into the length method.
Code:
Bikes={'Bike#1':'Bajaj','Bike#2':'Hero Honda','Bike#3':'Yamaha' }
print('Total bikes in the market',len(Bikes))
Output:
6. str()
The str() method is used for making a dictionary into a string format. this is more of a typecasting method. So typecasting means 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, the corresponding keys and values will be treated as a component of the string.
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 alike to normal 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.
- Any deletion and reinsertion in an ordered dictionary imply the deleted item to be hosted as a new and last item into the dictionary.
- Algorithmically, OrderedDict has been capable to seize intermittent reshuffle practice well over again than normal dictionaries.
Functions in Python Dictionary
The key functions used in a dictionary are as below:
Functions | Description |
Python Dictionary clear() | Removes all Items |
Python Dictionary copy() | Returns Shallow Copy of a Dictionary |
Python Dictionary fromkeys() | Creates a dictionary from the given sequence |
Python Dictionary get() | Find the value of a key |
Python Dictionary items() | returns view of dictionary’s (key, value) pair |
Python Dictionary keys() | Prints the keys |
Python Dictionary popitem() | Remove the last element of the dictionary |
Python Dictionary setdefault() | Inserts Key With a Value if Key is not Present |
Python Dictionary pop() | removes and returns element having given key |
Python Dictionary values() | returns view of all values in the dictionary |
Python Dictionary update() | Updates the Dictionary |
Code:
from collections import OrderedDict
Veichles_ordered_dict=OrderedDict({'Bike1':'yamaha','Bike2':'honda','Bike3':'bajajpito','Bike4':'pulser','Bike5':'apache','Bike6':'enfield','Bike7':'enfieldclassic','Bike8':'KTM','Bike9':'Splendor','Bike10':'fazer','Bike11':'hondawing','Bike12':'marlbaro','Bike13':'harleydavidson','Bike14':'kymco','Bike15':'guzzi','Bike16':'moped','Bike17':'mahinderamojo','Bike18':'bmw','Bike19':'audi','Bike20':'bmwk1600','Car1':'fiat','Car2':'honda-civic','Car3':'sonato','Car4':'i10','Car5':'i20','Car6':'esteem','Car7':'alto','Car8':'ciaz','Car9':'honda-city','Car10':'baleno','Car11':'jeep','Car12':'tata-seiro','Car13':'tat-nano','Car14':'bentley','Car15':'ferrari','Car16':'jaguar','Car17':'mahindera','Car18':'bmw','Car19':'audi','Car20':'GLO'})
Veichles_ordered_dict['Bike21']= 'TVS50'
Veichles_ordered_dict['Car20']= 'ford'
print(" ")
print(" ALL KEYES IN VEICHLES ")
print('print the keys :', Veichles_ordered_dict.keys())
print(" ")
print(" ALL VALUES IN VEICHLES ")
print('print the Values :', Veichles_ordered_dict.values())
Output:
Examples to Implement in Python Dictionary
Below are some examples explained with proper implementation.
Example #1
Code:
# dicitonary creation
dict_1 = {1:1, 2:2, 3:9, 4:16, 5:25 , 6:36 , 7:49}
# item deleteion
print( " ITEM DELETION ")
print(dict_1.pop(3))
print(" ")
print(" Dictionary after deletion " )
# Output: {1: 1, 2: 4, 4: 16, 5: 25}
print(dict_1)
print(" ")
print(" Arbitary item removal " )
# arbitary 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()
# Output: {}
print(dict_1)
Output:
The Explanation for the above code: The above example involves the process of dictionary creation using an unusual and indexed deletion of the dictionary items. The process of deletion is achieved by means of 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.
Example #2
Code:
Vechiles = {}
#Variable declaration
Bike_keys=['Bike#1','Bike#2','Bike#3','Bike#4','Bike#5','Bike#6','Bike#7','Bike#8','Bike#9','Bike#10','Bike#11','Bike#12','Bike#13','Bike#14','Bike#15','Bike#16','Bike#17','Bike#18','Bike#19','Bike#20']
Bike_values = ['yamaha','honda','bajajpito','pulser','apache','enfield','enfieldclassic','KTM','Splendor','fazer','hondawing','marlbaro'
,'harleydavidson','kymco','guzzi','moped','mahinderamojo','bmw','audi','bmwk1600']
`Car_keys=['Car#1','Car#2','Car#3','Car#4','Car#5','Car#6','Car#7','Car#8','Car#9','Car#10',
'Car#11','Car#12','Car#13','Car#14','Car#15','Car#16','Car#17','Car#18','Car#19','Car#20']
Car_values=['fiat','honda-civic','sonato','i10','i20','esteem','alto','ciaz','honda-city','baleno','jeep','tata-seiro'
,'tat-nano','bentley','ferrari','jaguar','mahindera','bmw','audi','GLO']
# Casting and Zipping Keys with values
Bikes=dict(zip(Bike_keys,Bike_values))
Cars=dict(zip(Car_keys,Car_values))
Bikes.update(Cars)
Vechiles = Bikes.copy()
#Print Section
print(" ")
print(" BIKES IN THE MARKET ")
print(Bikes)
print(" ")
print(" CARS IN THE MARKET ")
print(Cars)
print(" ")
print(" ALL VEICHLES IN THE MARKET ")
print(Vechiles)
Output:
The Explanation for the above code: In the above example involves the process of dictionary creation using an unusual method of casting and merging two different entities. The program involves collecting values into two different lists. The first list acts as the dictionary Bikes’ key items; the second list acts as the dict Bikes’ values. Then both the individual lists are fused into a single dictionary item. The above process is repeated for a different list of car keys and values. In the code’s successive section, these individual dictionaries, which were zipped from a separate list, are joined together. The update() method is used for achieving this joining process. The dictionary to joined is updated as an item into another dictionary element, which results in a brand new dictionary that is a combination of both the below above given dictionary items.
Conclusion
Collection data types hold a superior role in all standard programming languages in the market. In such cases, python’s dictionary component offers a large space for sophisticated data handling in python. The varied set of methods in these dictionary items offer a large instance of techniques to perform upon the data entities.
Recommended Articles
This is a guide to Dictionary in Python. Here we discuss 6 methods, key functions and 2 examples of implementing Dictionary in Python. You can also go through our other related articles to learn more-
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses