Comprehensive Python

Table Of Contents:

Python Datatypes: Dictionary

Ladies and Gentlemen, the journey to our python programming is never a reverse trip, This is the fifth tutorial of Our datatypes tutorial...
I am Proud to say welcome to you all to this edition of our series...

Unfortunately, I never forget easily, I know and I remember so well that in Our Getting Started tutorial, we did and covered some of the basics of Python dictionaries,
Which follows that if you jumped into a moving train, we recommend that you turn back to the depot.

Now that we understand something about Lists, and Tuples, the shift to python dictionaries will be mercifully easier to adapt.

Python Dictionaries


Python dictionaries are the essential and formal way for storing data. just like real world dictionaries, that actually contain words and their meanings, the python dictionaries store data with keys and their values.
In real world dictionaries, the python key would be a word and value would be a meaning.
Compare the following for easy understanding:

English Go : to move on a course

Python {'Go':'to move on a course'}

As can be seen on the examples above, the difference between the real world dictionaries and the python dictionaries is that:
Python dictionaries encloses the key(word) and the value(meaning) in the braces { } while real world dictionaries do not... If you also look closely, the data in Python dictionaries are enclosed in quotes. That is the existing differences between the real world dictionaries and the python dictionaries.
Now lets take a look at how we can add or access items from the python dictionaries.

Working With Dictionaries

Unlike Python lists and other data types, Python dictionaries has two parts to deal with than just adding items one by one.
To initialize the python dictionary, you'll need to assign { } to a variable or itself.
All the elements of a dictionary goes in it during the insertions or assignments. Here is how we can initialize a python dictionary:

>>> Dictionary = {}

Therefore, we can assign values to this variable as described below:

>>> Dictionary['name'] = 'Amin'

Now as you can see, instead of using indeces, in python dictionaries, we make use of keys.
The part in [ ] is the dictionary key, representing the dictionary value Amin.
To assign a value in a dictionary, we need to assign it during definition, as
>>> Ages = {'amin':23, 'george':23, 'blessings':23}
Or you can assign it later as follows:
>>> Ages['Salvation'] = 23
You can also edit/change the contents of a dictionary key as follow:
>>> Ages['amin'] = 30
As if this is not enough, you can also remove or delete elements in a dictionary by using del, used in the tuples.
You can achieve this as described in the following example:
>>> del Ages['amin']
>>> print(Ages) # {'george':23, 'blessings':23, 'Salvation':23}
below versed will expand almost all the usable python dictionary functions in details...

Python dictionary Functions

Now, lettake a look at the way we can use the dictionary's buikt in function and use them to manipulate our data/programs.
Unlike previous Tuples, this dictionary thing has got somehow better amount of functions.
Some of this functions are those that you already encountered in the previous lessons and I hope by for now, you are familliar with them. To begin with, let's take a look at:
.clear()
This function, as used in lists, removes all the elements in the python dictionary.
It however doesnt return anything once called.
The usage of the dictionary function clear() is:
>>> dictionary = {'name':'Amin', 'lname':'Matola'}
>>> print(dictionary) # {'name':'Amin', 'lname':'Matola'}
>>> dictionary.clear()
>>> print(dictionary) # {}

.copy()
This function, too, has been met during our list manipulations and no wonder, this function does pretty same as we did in lists.
this function copies the contents of the dictionary into another variable, where the original and the new dictionahry has the simillar contents. The original contents therefore always remain the same...
The proper usage of this function might be as in the below examples:
>>> d1 = {'name':'Amin', 'lname':'Matola'}
>>> d2 = d1.copy()
>>> print(d1) # {'name':'Amin', 'lname':'Matola'}
>>> print(d2) # {'name':'Amin', 'lname':'Matola'}

.fromkeys(iterable, value)
This function is recently strange to us, as we did not meet it, during our discussion on Numbers, Strings etc. As said earlier, the python dictionaries are comprised of keys and values.
This function however, changes a dictionary with the iterables as keys, and optional value as the default value for the keys.
If value is not set, then the default value of None is set for all the keys. Below is how we can correctly use this function.
>>> d = {'Name':'Amin', 'Location':'Chilomoni'}
>>> print({}.fromkeys({*d})) # {'Location':None, 'Name':None}
>>> d2 = d.fromkeys(['Owner', 'Gender'], 'Amin')
>>> print(d2) # {'Owner':'Amin', 'Gender':'Amin'}

.get(key, default=None)
As the name narrates, this function gets an item from the dictionary. It takes two arguments, the key and an optional default value.
The key is the name of the item in the dictionary whose value shall be returned, and the default is the value to be returned in case the item do not exist in the dictionary.
The default is always set to None, which means, if the item does not exist in the dictionary, then nothing will be returned.
Here is how we can use this function correctly:
>>> d = {'Name':'Amin', 'Location':'Chilomoni'}
>>> print(d.get('Name')) # 'Amin
>>> print(d.get('Date-Of-Birth')) #
>>> print(d.get('Date-Of-Birth', 'Not Available Here')) # Not Available Here

.items()
this function returns all the items present in the library in a set of key and its value.
The proper usage of this function goes like:
>>> d = {'person':'george','age':20}
>>> print(d.items()) # dict_items([('person', 'george'), ('age', 20)])

.keys()
This function returns a set-like object which contain the collection of all keys in the dictionary.
The usage goes as the example provided below.
>>> d = {'person':'george','age':20}
>>> print(d.items()) # dict_keys(['person', 'age'])
.pop(keys, default)
This function returns removes an item from the dictionary and returns its corresponding value.
This function is different from that we met in lists...
In dictionaries, if the key is not given, an IndexError is raised, else, it removes the provided key from the dictionary.
If the default is given, then instead of IndexError, the default is returned.
Take a look at the example provided below:
>>> dictionary = {'name':'coder', 'home':'here'}
>>> print(dictionary.pop()) # IndexError
>>> print(dictionary.pop('name')) # me
>>> print(dictionary.pop('falseItem','That is not available!')) # That is not available!

.popitem()
This function removes an item key and its value from the end of the dictionary and returns that key and value as a tuple.
Unlike the pop() function above, this function do not have parameters...
Therefore, it raises an keyError if the dictionary is empty.
>>> dictionary = {'name':'coder', 'home':'here'}
>>> print(dictionary.popitem()) # ('hone','here')
>>> print(dictionary.popitem()) # ('name','coder')
>>> print(dictionary.popitem()) # keyError

.setdefault(keys, default)
Honestly, I like this function in dictionary. This function takes a key and an optional value.
If the key is not available in the dictionary, the key and the value are inserted into the dictionary, and if the item is in the dictionary, its value is returned, else, the default value is returned. Take a look at the example provided below:
>>> dictionary = {'name':'coder', 'home':'here'}
>>> print(dictioanary.setdefault('other':'george')) # george
>>> print(dictionary.setdefault('other')) # george
>>> print(dictionary) # {'name':'coder', 'home':'here', 'other':'george'}

.update(E)
This function updates the existing dictionary. It takes an iterable parameter and whose values are to update the dictionary with.
This method would be, and is very easy if we learn by examples. Now drop your head to the code snippet below to get the full understanding.
>>> person = {'Name':'Amin','Home':'Blantyre'}
>>> print(person) # {'Name':'Amin', 'Home':'Blantyre'}
>>> people.update({'Home':'Machinga', 'Hobbies':'Programming'})
>>> print(person) # {'Name':'Amin', 'Home':'Machinga', 'Hobbies':'Programming'}

You can also achieve this using other none dictionary iterables like zipped lists and other a, b format data types. Look at the examples below;
>>> person = {'Name':'Amin'}
>>> person.update(Home = 'Machinga')
>>> person.update([('Hobbies', 'Programming')])
>>> person.update(zip(['Surname','Age'], ['Matola',23]))

All the above are the acceptable ways to update the python dictionary, so you may choose which one suits your needs.
The Zen Of Python says:
" There should be one-- and preferably only one --obvious way to do it "
I just taught all, so you may select which one is best for you.
.values()
As opposed to .keys(), this function returns all the values of the keys available in the dictionary. Without taking much of our time, lets look on how we can work with this nethod.
>>> person = {'Name': 'Amin','Surname': 'Matola'}
>>> headers= person.keys()
>>> print(headers) # ['Name', 'Surname']
>>> print(person.values()) # ['Amin', 'Matola']

Ladies and gentlemen, that marks the end of our today's lesson on the dictionary data type,
now, we have the opporunity to finish our datatype series with the Sets datatype.