Python Dictionary

Python has 4 built-in data types that are used to store collections of data, They are 

  1. List
  2. Tuple
  3. Set
  4. Dictionary

In this tutorial we will learn about Dictionary.

dictionary is a collection of objects which is unordered and mutable. Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’. And it consists of a key value pair.

Example

employee = {"name": "Surya", "id": 'SG1280', "role": 'Software Dev'}

print(employee)
{'name': 'Surya', 'id': 'SG1280', 'role': 'Software Dev'}

In the above example we have seen that we have created a dictionary known as employee, which consists of three key-value pairs where idname and role are the keys and Surya, SG1280 and Software Dev are their respective values.

Accessing Elements:

We can always access the elements inside the dictionary by using the ‘key’ name to access the ‘value’ of a dictionary.

Example:

employee = {"name": "Surya", "id": 'SG1280', "role": 'Software Dev'}
emp_name = employee['name']

print(emp_name)
Surya

Adding Elements:

We can add a new element in dictionaries by using key value pair e.g employee[Key] = ‘Value’.

Example:

employee = {"name": "Surya", "id": 'SG1280', "role": 'Software Dev'}
employee['location'] = 'hyderabad'

print(employee)
{'name': 'Surya', 'id': 'SG1280', 'role': 'Software Dev', 'location':'hyderabad'}

We can also change the existing element in the dictionary

employee = {"name": "Surya", "id": 'SG1280', "role": 'Software Dev'}
employee['name'] = 'Karthi'

print(employee)
{'name': 'Karthi', 'id': 'SG1280', 'role': 'Software Dev'}

Removing Items from a Dictionary:

You can remove the items in a dictionary as well by using the pop() function. For example if you want to remove name of the employee, then you can do that by naming ‘name’ inside the pop() parentheses.

Example:

employee = {"name": "Surya", "id": 'SG1280', "role": 'Software Dev'}
employee.pop('name')

print(employee)
{'id': 'SG1280', 'role': 'Software Dev'}

Set vs Dictionary

A set in python is a collection of items just like Lists and Tuples. Note the following about sets:

  • A set is created using the set keyword
  • A set cannot be an element of a set

A dictionary in python is a collections of key-value pairs of item. For each entry, there are two items: a key and a value. Note the following about Python dictionaries

  • keys in a dictionary must be unique
  • keys are immutable
  • keys and values can be of any data types
  • the keys() function returns list of keys in a dictionary
  • the values() function returns list of values in dictionary.

Python Dictionary
  1. dictionary is a collection of objects which is unordered and mutable.
  2. Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’. And it consists of a key value pair.