Codementor Events

Python Dictionary

Published Jan 23, 2019Last updated Jan 24, 2019
Python Dictionary

Introduction

  • It is one to one relation with the key to value but not value to key.
  • Dictionaries are Mutable and unordered data structures
  • Values of a dictionary can be any type (list, function, strings etc),
    but the keys must be of an immutable (numbers, strings, tuples etc) data type
  • If the keys will be mutable as there will be a chance of key duplication that will creating the confusion

download.png

Define a Dictionary

Dictionaries are written within curly brackets {}

 > mydict = {}   Empty Dictionary
 > mydict = {1:"one", 2:"two", 3:"three"}  Dictionary with items
 > mydict = dict() We can also create a dictionary object by calling its python built in dict() keyword

python_dictionary.jpg

We can check the type of a dictionary using

print(type(mydict)) --> <class 'dict'>

Access values from a dictionary

We can access dictionary values using square brackets [ ]
The below code uses the key python to access the value codementor

mydict = {'python':"codementor", 'good':"bad", 'hi':"hello"}
print(mydict['python'])

Output: codementor

If the key doesnot exist it will give KeyError. This error tells that there is no key called "python1" in the dictionary

print(mydict['python1'])

Output: 
Traceback (most recent call last):
  File "C:/dictionary.py", line 2, in <module>
    print(mydict['python1'])
KeyError: 'python1'

If we want to avoid this error we can use get() method. It will check the dictionary, if it doesn't contain the key it will give None as output

mydict = {0:"codementor", 1:"bad", 'hi':"hello"}
print(mydict.get(2))

Output:   None

Update keys

Updating the keys means adding keys to a dictionary

mydict = {0:"One", 1:"Two", 2:"Three"}
mydict.update({3:"Three", 4:"Four"})
print(mydict)
Output:
{0: 'One', 1: 'Two', 2: 'Three', 3: 'Three', 4: 'Four'}

Removing Keys

we can remove keys using two methods pop() & del()

  • The pop() will check if the key is in the dictionary or not
  • If the key is there it will remove the key
  • If the key is not there it will give KeyError
mydict = {0:"One", 1:"Two", 2:"Three"}
print(mydict.pop(5))
Output: 
Traceback (most recent call last):
  File "C:/dictionary.py", line 2, in <module>
    print(mydict.pop(5))
KeyError: 5

We can suppress the key error by passing a second argument

mydict = {0:"One", 1:"Two", 2:"Three"}
print(mydict.pop(5,None))

Output:  None
mydict = {0:"One", 1:"Two", 2:"Three"}
print(mydict.pop(0))
print(mydict)
Output:
One
{1: 'Two', 2: 'Three'}

  • The other way to remove items from a dictionary using pythons built-in del() method.
  • This will delete the specific key,value from a dictionary.
  • If the key isn't there it will give a KeyError.
  • That's why we actually use pop() method.
mydict = {0:"One", 1:"Two", 2:"Three"}
del mydict[1]
print(mydict)
Output: {0: 'One', 2: 'Three'}

Using keys() method we can access all the keys of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
print(mydict.keys())

Output: dict_keys([1, 2, 3, 4])

Using values() method we can access all the values of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
print(mydict.values())

Output: dict_values(['one', 'two', 'three', 'four'])

Using items() method we can access all the items(key,value) of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
print(mydict.items())

Output: dict_items([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])

Iterate through a dictionary

Python dictionary allows the programmer to iterate over it's keys, values using forloop. Let's look into this
We can iterate through the keys of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
for mykey in mydict.keys():
    print(mykey)
    
 Output:
 1
 2
 3
 4

iterate through the values of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
for myval in mydict.values():
    print(myval)
    
Output:
one
two
three
four

Iterate both keys&values of a dictionary

mydict = {1:"one", 2:"two", 3:"three", 4:"four"}
for key,val in mydict.items():
    print(key,":",val)

Output:
1 : one
2 : two
3 : three
4 : four

Methods of a dictionary

Methods Description
clear() The clear() method removes all the items from the dictionary
pop() Removes the element from a dictionary and returns it
get() This will give a value for a given key
update() Add key,value pair to a dictionary
keys() Return a list of keys in the dictionary
values() Return a list of values in the dictionary
items() Returns key,values from a dictionary
type() Return the type of the variable
copy() Copy the contents of the dictionary

For Practice Dictionary Exercises click here

This is all we have to know about Dictionaries. Practice more and more till you get this handy.

Discover and read more posts from Sadhana Reddy
get started
post comments3Replies
Usman Dembele
4 years ago

yes its very good to see this article really love it very informative it is i am also working on the similar topic project you can see here https://topbestnespresso.com/

sathya
6 years ago

Good article Sadhana…

Sadhana Reddy
6 years ago

Thank you sathya