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’}

Comments

Popular posts from this blog

CODING ASSIGNMENT 4

CODING PRACTICE 11 Music Page

CCBP Static Website Coding Assignment 2 Solution | Yoga Page