Sunday, January 17, 2021

Dictionary in Python

Introduction:

Dictionary is a versatile in-built data type in python. Dictionary are mutable, unordered collection with elements in the form of a key:value pairs that associated key to values.

Structure:

dictionary-name={key:value, key:value...}

Example:

student={"name":"John","roll":12,"Percentage":88.25}


Characters of a Dictionary:

  • Dictionary are undordered set of key:value pairs
  • Dictionary are not sequences like list,tuple,string etc as they are not indexed by number
  • Keys of the dictionary MUST BE UNIQUE
  • Dictionary are MUTABLE i.e. we can change the value of the key in place
  • Internally the key and value are mapped(connected) to each other by using some hash function. This way of linking is called mapping.

Creating Dictionary:

Syntax:
dictionary-name={key:value, key:value...}

Sample data:
roll: 12 13 14
name: john tom jason

In [2]:
stu={12:"John",13:"tom",14:"jason"}  #here roll acts keys and name acts as values
print(stu)
{12: 'John', 13: 'tom', 14: 'jason'}

Note:  The keys of the dictionary must be of immutable type such as string,number,tuple

Creating dictionary using dict() function:

In [6]:
rl=[12,13,14]
nm=['John','Tom','Jason']
stu=dict(Roll=rl,Name=nm)
print(stu)
{'Roll': [12, 13, 14], 'Name': ['John', 'Tom', 'Jason']}

Accessing/Traversing elements of Dictionary:

Value from the dictionary can be accessed using the key
Syntax:
dictionary_name[key]

In [22]:
stu={12:"John",13:"tom",14:"jason"}
print(stu[14])
jason
In [19]:
print(stu.keys())
dict_keys([12, 13, 14])
In [20]:
print(stu.values())
dict_values(['John', 'tom', 'jason'])

Traversing using loop:

In [10]:
for key in stu:
    print(key,' : ',stu[key])
12  :  John
13  :  tom
14  :  jason
In [12]:
for key,val in stu.items():
    print(key,' : ',val)
12  :  John
13  :  tom
14  :  jason
In [17]:
for key in stu.keys():
    print(key)
12
13
14
In [18]:
for key in stu.values():
    print(key)
John
tom
jason

Adding Elements to a Dictionary:
Syntax:   dictionary_name[key]=value

In [23]:
stu={12:"John",13:"tom",14:"jason"}
stu[15]="Harry"
print(stu)
{12: 'John', 13: 'tom', 14: 'jason', 15: 'Harry'}

Updating Elements to a Dictionary:
Syntax:   dictionary_name[key]=value

In [24]:
stu={12:"John",13:"tom",14:"jason",15: 'Harry'}
stu[14]="Dwayn"
print(stu)
{12: 'John', 13: 'tom', 14: 'Dwayn', 15: 'Harry'}

Deleting Elements from a Dictionary:  Del command and pop() function can be used

  • Using del:   del dictionary_name[key]  Just deletes the key-value pair
  • Using pop():   dictionary_name.pop(key)  deletes the key-value pair and returns the value

In [2]:
stu={12:"John",13:"tom",14:"jason"}
print(stu)
del stu[14]
print(stu)
{12: 'John', 13: 'tom', 14: 'jason'}
{12: 'John', 13: 'tom'}
In [4]:
stu={12:"John",13:"tom",14:"jason"}
print(stu)
val=stu.pop(14)
print(stu)
print(val)
{12: 'John', 13: 'tom', 14: 'jason'}
{12: 'John', 13: 'tom'}
jason

Dictionary Methods and built-in Function:

len(dictionary_name):  Return the number of key:value pair in the dictionary

In [6]:
stu={12:"John",13:"tom",14:"jason"}
print(len(stu))
3

dict(**kwargs):   This function creates a dictionary

In [11]:
dc=dict(x=5, y=0)
print(dc)
{'x': 5, 'y': 0}

dictionary_name.keys()  Returns all the keys of the dictionary

In [15]:
stu={12:"John",13:"tom",14:"jason"}
print(stu.keys())
dict_keys([12, 13, 14])

dictionary_name.values()  Returns all the values of the dictionary

In [16]:
stu={12:"John",13:"tom",14:"jason"}
print(stu.values())
dict_values(['John', 'tom', 'jason'])

dictionary_name.items()   Returns all the key:value pair in the dictionary

In [18]:
stu={12:"John",13:"tom",14:"jason"}
print(stu.items())
dict_items([(12, 'John'), (13, 'tom'), (14, 'jason')])

dictionary_name.get(key,default)  Return the value of the key if present else return the Default value

In [20]:
stu={12:"John",13:"tom",14:"jason"}
print(stu.get(14,'Value not present'))
print(stu.get(15,'Value not present'))
jason
Value not present

dictionary1.update(dictionary2):   Updates the content of dictionary1 from dictionary2 based on matching index

In [21]:
emp1={'name':'John','Salary':10000,'age':24}
emp2={'name':'Diya','Salary':25000,'dept':'sales'}
emp1.update(emp2)
print(emp1)
{'name': 'Diya', 'Salary': 25000, 'age': 24, 'dept': 'sales'}

dictionary_name.clear()   removes all the elements from the dictionary

In [23]:
stu={12:"John",13:"tom",14:"jason"}
stu.clear()
print(stu)
{}

dict.fromkeys(keys, value)  Method returns a dictionary with the specified keys and the specified value.

In [27]:
roll = (12,13,14)
name = ("John")

stu = dict.fromkeys(roll, name)
print(stu)
{12: 'John', 13: 'John', 14: 'John'}

dictionary1.copy()  Returns a shallow copy of the dictionary. It doesn't modify the original dictionary.

In [28]:
stu={12:"John",13:"tom",14:"jason"}
stu1=stu.copy()
print(stu1)
{12: 'John', 13: 'tom', 14: 'jason'}

dictionary_name.popitem()  Remove and return the last item of the dictionary

In [29]:
stu={12:"John",13:"tom",14:"jason"}
val=stu.popitem()
print(val)
(14, 'jason')

max(dictionary_name)  Return the maximum index from the dictionary

In [31]:
stu={12:"John",13:"tom",14:"jason"}
print(max(stu))
14

min(dictionary_name)  Return the minimum index from the dictionary

In [37]:
stu={12:"John",13:"tom",14:"jason"}
print(min(stu))
12

Practice Question:

  1. Write a program that repeatedly asks the user to enter product and price. Store all of these in a dictionary whose keys are the product names and whose values are the prices.
  1. Given two dictionaries say D1 and D2. Write a program that lists the overlapping keys of the dictionary, i.e. if a key of D1 is also a key of D2, then list it.
  1. write a program to count the number of times a character appears in a given string using a dictionary
  1. Write a program to create a dictionary with names of employees, their salary and access them.
Share: