7

6TH DATATYPE: DICTIONARY

by

The Education Machine

[support@theeducationmachine.com]

Dictionary Datatype

Think of a dictionary datatype just like an english dictionary where words and their meanings are mapped with each other.

Dictionary in python stores key value pairs.

Dictionaries can be created using curly braces { } or using dict() function.

They are used for faster retrieval of data. You can relate it to JSON/parquet format.

Don't get confused since curly braces also used to create sets. Remember,sets are just the collection of elements.

Lists, Tuples and Strings were ordered datatypes which means they can be indexed using numbers starting from 0.

However, Dictionaries are unordered which means they cannot be indexed using numbers but keys works as index for it.


Syntax to define a dictionary:

  d = {'age': 10, 'name': 'XYZ', 'address': 'DELHI'}
  print(d, type(d))


Output:
{'age': 10, 'name': 'XYZ', 'address': 'DELHI'} <class 'dict'>

Lets now try indexing on any element of above dictionary. Note the error, hence number indexing is not possible in dictionaries.

  d = {'age': 10, 'name': 'XYZ', 'address': 'DELHI'}
  d[1]

reserved_keywords

Indexing can be done in dictionary using keys:

  d = {'age': 10, 'name': 'XYZ', 'address': 'DELHI'}
  d[1]


Output:
'DELHI'

To define a dictionary using dict() function.

   d = dict(age= 10, name= 'XYZ', address= 'DELHI')
  print(d,type(d))


Output:
{'age': 10, 'name': 'XYZ', 'address': 'DELHI'} <class 'dict'>