Saturday, July 11, 2020

Python Dictionary with examples



Hello guys! Welcome back to another section of my tutorial on Python. In this tutorial guide, we will be studying about the Python Dictionary.

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole stuff is been enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but they keys must be a fixed data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to be able to obtain its value.

Example

Following is a simple example -

#!/usr/bin/python

dict = {'Name': 'Paul', 'Age': 20, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Output

Below is the output of the above example -

dict['Name']:  Paul
dict['Age']:  20

RECOMMENDED POST: Python Tuples with examples 

If we attempt to access a data item with a key, which is not a part of the dictionary, then we get an error as follows -

#!/usr/bin/python

dict = {'Name': 'Paul', 'Age': 20, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

Output

Below is the output of the above example -

dict['Alice']:
Traceback (most recent call last):
   File "test.py", line 4, in <module>
      print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

Updating Dictionary

You can update a dictionary by including a new entry or key-value pair, by modifying an existing entry, or deleting an existing entry as shown in the simple example below -

#!/usr/bin/python

dict = {'Name': 'Paul', 'Age': 20, 'Class': 'First'}
dict['Age'] = 22; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Output

Below is the output of the above example -

dict['Age']:  22
dict['School']:  DPS School


Deleting Dictionary Elements

You can either remove the individual dictionary elements or even clear the entire dictionary contents. You can also  delete the entire dictionary in a single operation.

I order to explicitly remove an entire dictionary, just use the del statement.

Example

Following is a simple example -

#!/usr/bin/python

dict = {'Name': 'Paul', 'Age': 20, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

Output

This produces the following result. Note - That an exception is raised because after del dic, dictionary does not exist anymore.

dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in <module>
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable


Properties of Dictionary Keys

Python dictionary values have no restrictions. They can be any  Python object, either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to take note of about dictionary keys -

(a) - More than one entry per key is not allowed. Which means that no duplicate key is allowed. When any duplicate keys are being encountered during an assignment, then the last assignment wins.

Example
Following below is a simple example -

#!/usr/bin/python

dict = {'Name': 'Paul', 'Age': 20, 'Name': 'Sophia'}
print "dict['Name']: ", dict['Name']

Output

Below is the output of the above example -

dict['Name']:  Sophia

(b) - Keys must be immutable. Which means you can use strings, numbers, or even tuples as Python dictionary keys but something like ['keys'] is not allowed.

Example

Following is a simple example -

#!/usr/bin/python

dict = {['Name']: 'Paul', 'Age': 20}
print "dict['Name']: ", dict['Name']

Output

Below is the output of the above example -

Traceback (most recent call last):
   File "test.py", line 3, in <module>
      dict = {['Name']: 'Paul', 'Age': 20};
TypeError: unhashable type: 'list'



Built-in Python Dictionary Functions
Following below is a list of dictionary functions that included by Python -

Sr.No.Function with Description
1cmp(dict1, dict2)
Compares elements of both dict.
2len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3str(dict)
Produces a printable string representation of a dictionary
4type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.


Buit-in Python Dictionary Methods
Following below is a list of dictionary methods available in Python -

Sr.No.Methods with Description
1dict.clear()
Removes all elements of dictionary dict
2dict.copy()
Returns a shallow copy of dictionary dict
3dict.fromkeys()
Create a new dictionary with keys from seq and values setto value.
4dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5dict.has_key(key)
Returns true if key in dictionary dictfalseotherwise
6dict.items()
Returns a list of dict's (key, value) tuple pairs
7dict.keys()
Returns list of dictionary dict's keys
8dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
10dict.values()
Returns list of dictionary dict's values


Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial, we are going to be studying about Python the dictionary cmp() Method.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.