Python Programming for beginners. Pt 4 – Dictionaries Concept

image source : python shell (screenshot)

By : Bijay Acharya / studentvideotutorial

Well, welcome to Part 4. Here, I’ll give you the basic concepts on Dictionaries when it comes to programming in Python.
– The Python dictionary data structure provides a hash table that can store any number of Python objects. The dictionary consists of pairs of items that contain a KEY and VALUE. 
– When constructing a dictionary, each KEY is separated from a value by a colon (:), and we separate items by Commas (,).
The complete Code looks like this [Note: Explanation of each line of code is provided below the code]:
>>> services = {‘ftp’:21, ‘ssh’:22, ‘smtp’:25, ‘http’:80}
>>> services.keys()
[‘ftp’, ‘http’, ‘smtp’, ‘ssh’]
>>> services.items()
[(‘ftp’, 21), (‘http’, 80), (‘smtp’, 25), (‘ssh’, 22)]
>>> services.has_key(‘ftp’)
>>> services[‘ftp’]
>>> print “[+] Found vuln with FTP on port “+str(services[‘ftp’])
[+] Found vuln with FTP on port 21
Let’s see first line of code:
services = {‘ftp’:21, ‘ssh’:22, ‘smtp’:25, ‘http’:80}  – Here, we’re creating a dictionary named ‘services‘, and the KEYs are ftp,ssh,smtp,http . . . which are separated from VALUEs by colons. [Note: values are 21,22,25,80] . . . And, these four items are separated by commas.
The second line of code:
services.keys()  – .keys() is method that will return all the keys in dictionary.
The third line of code:
services.items()  – .items() is method that will return the entire list of items in dictionary.
The fourth line of code:
services.has_key(‘ftp’)  – it’s a kind of question like Has Key FTP ? . . . If yes, then the value returns TRUE.

Well, this was about creating a Dictionary in Python. References: Violent Python PDF, Cybrary Study Materials and Python.Org