Dictionaries

 

Introduction to Dictionaries

  • a set of  key: value pairs

student={ ‘Rollno’:101 , ‘Name’ : ‘Abc’ }

The pairs are separated by comma ( , ) and all the pairs are inserted into { } brackets. The name of the dictionary is student.

If the key is provided we can get its value.

Duplicate keys are not allowed , if same keys are entered, the old key will be replaced by new value

Keys are immutable :

we can use number, string or tuples as keys.

we cannot use list or directories as keys

Operations on Dictionaries

1.Length of dictionary

n = len(student)

2.Modify the existing values

student[‘Name’]= ‘xyz’

3.Delete the dictionary pair

del student[‘Rollno’]

  1. To view dictionary

print(student)

  1. Check if key exist

Name’ in student // it returns true

‘Marks’ in student // it returns false


Dictionary Methods

  • Remove all key value pairs

student.clear()

  • Copy all elements

st = student.copy()

  • Create a new dictionary from specified keys and values

keys = {‘a', ‘b', ‘c', ‘d', ‘e' }

value = 1

st.fromkeys( keys, value )

  • Get value associated with the key

student.get(‘Rollno’) // it returns 101

  • Get key value pairs

student.items()

  • Get sequence of all keys

student.keys()

  • Get sequence of all values

student.values()

  • Adds all elements of dictionary x_students to students.

student.update(x_students)

  • Removes the key and its value from student and returns the value

student.pop(‘Rollno’)

  • If key is found it returns the value and if not found the key value pair is stored

student.setdefault(‘Marks’, 10)

It inserts a new key value pair returns the value 10

  • To print all values using loop

for s in student:

print(s)

Converting List into Dictionary

To convert list to dictionary there are two steps:

  1. Create zip class object by passing the two list to zip function.

  2. The second step is convert the zip object into a dictionary, using dict() function.

  • Suppose we have two lists :

  • subject = [ “maths”, “science”, “english“ , “computer” }

  • marks = [ 45, 50, 42, 46 ]

  • Zip function converts sequences into zip class object

z = zip(subject, marks )

The Dict function converts the zip object to dictionary.. The 0th element becomes key and 1st element becomes value and so on…

d = dict(z)

for k in d:

print( k, d[k])


Passing dictionaries to functions

  • Passing a dictionary to a function by passing name of the directory as parameter

  • Defining the function

def myfun(std)

for i, j in std.items():

print( i, “ ”, j )

  • Calling the function

student={ ‘Rollno’:101 , ‘Name’ : ‘Abc’ }

myfun( student ) // here dictionary student is passed as a parameter

Example:

#program of dictionary

student={'rollno':1,'name':'abc'}


n=len(student)

print("No of key value pair is",n)

student['result']=70.0

n=len(student)

print("No of key value pair is",n)

print(student)

student['result']=75.0

print(student)

del student['result']

print(student)

if( 'result' not in student):

print("Result key is not in student")

#key should be unique

#dictionary methods

s1=student.copy()

print(s1)

print(student)

keys={'a', 'b', 'c', 'd','e' }

value = 1

s=dict.fromkeys( keys,value)

print('new dictionary', s)

print('it returns the associated value of the key ',student.get('name'))

tp=student.items()

print('items method returns associated key and value pairs', tp)


print("All the keys from dictionary", student.keys())

print("All the values from dictionary", student.values())

s.update(student)

print("update s from student",s)

s.pop('a')

print(s)

print('To print all the keys from student')

for st in student:

print(st)

print('To print all the values from student')

for st in student:

print(student[st])

print('To print all the key -values from student')

for st in student:

print(st,"-",student[st])

#list to dictionary conversion

subject = [ 'maths', 'science', 'english','computer']

marks = [ 45, 50, 42, 46 ]

z = zip(subject, marks )

d=dict(z)

print(d)

Output:

'No of key value pair is', 2)

('No of key value pair is', 3)

{'name': 'abc', 'rollno': 1, 'result': 70.0}

{'name': 'abc', 'rollno': 1, 'result': 75.0}

{'name': 'abc', 'rollno': 1}

Result key is not in student

{'name': 'abc', 'rollno': 1}

{'name': 'abc', 'rollno': 1}

('new dictionary', {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1})

('it returns the associated value of the key ', 'abc')

('items method returns associated key and value pairs', [('name', 'abc'), ('rollno', 1)])

('All the keys from dictionary', ['name', 'rollno'])

('All the values from dictionary', ['abc', 1])

('update s from student', {'a': 1, 'c': 1, 'b': 1, 'e': 1, 'd': 1, 'rollno': 1, 'name': 'abc'})

{'c': 1, 'b': 1, 'e': 1, 'd': 1, 'rollno': 1, 'name': 'abc'}

To print all the keys from student

name

rollno

To print all the values from student

abc

1

To print all the key -values from student

('name', '-', 'abc')

('rollno', '-', 1)

{'maths': 45, 'science': 50, 'computer': 46, 'english': 42}