Python 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
}
PYTHON

Key - Value Pairs

Code

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

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)
PYTHON

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

Creating Empty Dictionary

Code - 1

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

Output

<class 'dict'>
{}

Code - 2

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

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'])
PYTHON

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'))
PYTHON

Output

Teja

Code

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

Output

None

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'])
PYTHON

Output

KeyError: 'city'
Quick Tip
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.

Membership Check

Checks if the given key exists.

Code

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

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)
PYTHON

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)
PYTHON

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)
PYTHON

Output

{'name': 'Teja'}

Dictionary Views

They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

Dictionary Methods

  • dict.keys()
    • returns dictionary Keys
  • dict.values()
    • returns dictionary Values
  • dict.items()
    • returns dictionary items(key-value) pairs

The objects returned by

keys()
,
values()
&
items()
are View Objects .

Getting Keys

The

keys()
method returns a view object of the type dict_keys that holds a list of all keys.

Code

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

Output

dict_keys(['name', 'age'])

Getting Values

The

values()
method returns a view object that displays a list of all the values in the dictionary.

Code

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

Output

dict_values(['Teja', 15])

Getting Items

The

items()
method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

Code

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

Output

dict_items([('name', 'Teja'), ('age', 15)])

Iterate over Dictionary Views

Example - 1

Code

dict_a = {
'name': 'Teja',
'age': 15
}
for key in dict_a.keys():
print(key)
PYTHON

Output

name
age

Example - 2

Code

dict_a = {
'name': 'Teja',
'age': 15
}
keys_list = list(dict_a.keys())
print(keys_list)
PYTHON

Output

['name', 'age']

Example - 3

Code

dict_a = {
'name': 'Teja',
'age': 15
}
for value in dict_a.values():
print(value)
PYTHON

Output

Teja
15

Example - 4

Code

dict_a = {
'name': 'Teja',
'age': 15
}
for key, value in dict_a.items():
pair = "{} {}".format(key,value)
print(pair)
PYTHON

Output

name Teja
age 15

Dictionary View Objects

keys()
,
values()
&
items()
are called Dictionary Views as they provide a dynamic view on the dictionary’s items.

Code

dict_a = {
'name': 'Teja',
'age': 15
}
view = dict_a.keys()
print(view)
dict_a['roll_no'] = 10
print(view)
PYTHON

Output

dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'roll_no'])

Converting to Dictionary

dict(sequence)
takes any number of key-value pairs and converts to dictionary.

Code

list_a = [
("name","Teja"),
["age",15],
("roll_no",15)
]
dict_a = dict(list_a)
print(dict_a)
PYTHON

Output

{'name': 'Teja', 'age': 15, 'roll_no': 15}

Code

list_a = ["name", "Teja", 15]
dict_a = dict(list_a)
print(dict_a)
PYTHON

Output

ValueError: dictionary update sequence element #0 has length 4; 2 is required

Type of Keys

A dictionary key must be of a type that is immutable.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form