Dictionaries in Python | Operations on Dictionaries | Cheat Sheet

Dictionaries

Unordered collection of items.

Every dictionary item is a Key-value pair.

Creating a Dictionary

Created by enclosing items within {curly} brackets

Each item in dictionary has a key – value pair separated by a comma.

Code

dict_a = {
  "name": "Teja",
  "age": 15 
}

Key – Value Pairs

Code

dict_a = {
  "name": "Teja",
  "age": 15 
}

In the above dictionary, the

  • keys are name and age
  • values are Teja and 15

Collection of Key-Value Pairs

Code

dict_a = { "name": "Teja",
            "age": 15 }
print(type(dict_a))
print(dict_a)

Output
<class ‘dict’>
{‘name’: ‘Teja’,’age’: 15}

Immutable Keys

Keys must be of immutable type and must be unique.

Values can be of any data type and can repeat.

Code

dict_a = {
  "name": "Teja",
  "age": 15,
  "roll_no": 15
}

Creating Empty Dictionary

Code – 1

dict_a = dict()
print(type(dict_a))
print(dict_a)

Output
<class ‘dict’>
{}

Code – 2

dict_a = {}
print(type(dict_a))
print(dict_a)

Output
<class ‘dict’>
{}

Accessing Items

To access the items in dictionary, we use square bracket [ ] along with the key to obtain its value.

Code

dict_a = {
  'name': 'Teja',
  'age': 15
}
print(dict_a['name'])

Output
Teja

Accessing Items – Get

The

get() method returns

None if the key is not found.

Code

dict_a = {
  'name': 'Teja',
  'age': 15
}
print(dict_a.get('name'))

Output
Teja

KeyError

When we use the square brackets

[] to access the key-value, KeyError is raised in case a key is not found in the dictionary.

Code

dict_a = {'name': 'Teja','age': 15 }
print(dict_a['city'])

Output

KeyError: ‘city’

If we use the square brackets [],  KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

Code

dict_a = {
  'name': 'Teja',
  'age': 15
}
print(dict_a.get('city'))

Output

None

Membership Check

Checks if the given key exists.

Code

dict_a = {
  'name': 'Teja',
  'age': 15
}
result = 'name' in dict_a
print(result)

Output

True

Operations on Dictionaries

We can update a dictionary by

  • Adding a key-value pair
  • Modifying existing items
  • Deleting existing items

Adding a Key-Value Pair

Code

dict_a = {'name': 'Teja','age': 15 }
dict_a['city'] = 'Goa'
print(dict_a)

Output

{‘name’: ‘Teja’, ‘age’: 15, ‘city’: ‘Goa’}

Modifying an Existing Item

As dictionaries are mutable, we can modify the values of the keys.

Code

dict_a = {
    'name': 'Teja',
    'age': 15
}
dict_a['age'] = 24
print(dict_a)

Output

{‘name’: ‘Teja’, ‘age’: 24}

Deleting an Existing Item

We can also use the

del keyword to remove individual items or the entire dictionary itself.

Code

dict_a = {
  'name': 'Teja',
  'age': 15
}
del dict_a['age']
print(dict_a)

Output

{‘name’: ‘Teja’}

Related Posts

Python Program to Convert Integer into a Single Numeral

Single Digit Number Ram is given a positive integer N .He wishes to convert this integer into a single numeral. He does so by repeatedly adding the…

Python Program to Print Armstrong numbers between two intervals

Write a program to print all the Armstrong numbers in the given range A to B (including A and B). An N – digit number is an…

Python Program to Check if Given Input is a Letter, Digit or Special Character

Letter, Digit or Special Character You are given a character as input. Check if the given input is a Lowercase Letter or Uppercase Letter or Digit or…

Interleave Strings | Python Program to merge two strings by adding characters in alternating order

Interleave Strings Given two strings, write a program to merge the given two strings by adding characters in alternating order, starting with the first string. If a…

Python Program to Check if given colors are present in the color palate

Shekhar is an artist. He likes to draw and paint. He is now drawing a portrait of a city road which is in the black color and…

Python Program to Check the eligibility criteria for donor  

Python Comparison Operators An XYZ hospital has organised a blood donation camp. The eligibility criteria for donor was as follows  1) Age>=18  2) Weight >=50 kg  3)…

Leave a Reply

Your email address will not be published.