Traversing a Dictionary and Dictionary Methods

M3-R5.1 · Chapter 5: Sequence Data Types · 13 min read

Traversing a Dictionary:

Syntax:

       for <variable-name> in <dictionary-name>:

                    statement

Example:

marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

for i in marks:

    print(i, ": ", marks[i])

OUTPUT:    Physics : 75

Chemistry : 78

Maths : 81

CS : 78

Change and add the value in a dictionary:

                     After adding a value to a dictionary we can then modify the existing dictionary element. we use the key of the element to change the corresponding value.

Syntax:

                dictionary-name[key]=value

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> marks

                      {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 78}

>>> marks['CS']=84     #Changing a value

>>> marks

          {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

>>> marks['English']=89    # Adding a value

>>> marks

                    {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}

        dict1= {"Company": "Toyota", "model": "Innova","year": 2012 }

        dict1["year"]=2014

        print(dict1)

 Output:

          {’year’:2014,’model’:’Innova’,’Company’:’Toyota’}

Delete elements from a dictionary:

There are two methods to delete elements from a dictionary:

         (i) using del statement        (ii) using pop( ) method

(i) Using del statement:  The del keyword can be used to remove the element with the specified key.

Syntax:

               del dictionary-name[key]

Example:

>>> marks

                {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}

>>> del marks['English']

                  >>> marks

                                      {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

We called the del keyword followed by the dictionary name. Inside the square brackets that follow the dictionary name, we passed the key of the element we need to delete from the dictionary,

(ii) Using pop( ) method: It deletes the key-value pair and returns the value of deleted element.

Syntax: dictionary-name.pop( )

Example:

>>> marks

             {'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84}

>>> marks.pop('Maths')

        81

The popitem() : The popitem() method removes the last item of inserted into the dictionary,without needing to specify the key. Take a look at the following example:

dict1 = {"Company":"Toyota","model": "Innova","year":2012 }

            dict1.popitem()

             print(dict1)

        Output:  {’Company’:’Toyota’,’model’:’Premio’}

 The last entry into the dictionary was "year". It has been removedafter calling the popitem() function.

Check The Existence Of A Key In A Dictionary:

To check the existence of a key in dictionary, two operators are used:

(i) in : it returns True if the given key is present in the dictionary, otherwise False.

(ii) not in : it returns True if the given key is not present in the dictionary, otherwise     False.

Example:

>>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

>>> 'Chemistry' in marks

        True

>>> 'CS' not in marks

         False

>>> 78 in marks # in and not in only checks the existence of keys not values

           False

DICTIONARY FUNCTIONS: Consider a dictionary marks as follows:

            >>> marks = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

Function

Description

Example

len( )

Find the length of a dictionary.

Syntax: len (dictionary-name)

>>> len(marks)

4

clear( )

removes all elements from the dictionary

Syntax: dictionary-name.clear( )

>>> marks.clear( )

>>> marks { }

get( )

Returns value of a key.

 Syntax: dictionary-name.get(key)

>>> marks.get("physics")

 75

Note: When key does not exist it returns no value without any error.

            >>> marks.get('Hindi')

items( )

returns all elements as a sequence of (key,value) tuples in any order.

Syntax: dictionary-name.items( )

>>> marks.items() dict_items([('physics', 75), ('Chemistry', 78), ('Maths', 81), ('CS', 78)])

Note: You can write a loop having two variables to access key: value pairs.

>>> seq=marks.items()

 >>> for i, j in seq:

               print(j, i)

OUTPUT: 75 physics

                  78 Chemistry

                 81 Maths

                 78 CS

keys( )

Returns all keys in the form of a list.

Syntax: dictionary-name.keys( )

>>> marks.keys()

dict_keys (['physics', 'Chemistry', 'Maths', 'CS'])

values( )

Returns all values in the form of a list.

Syntax: dictionary-name.values( )

>>> marks.values()

    dict_values([75, 78, 81, 78])

update( )

Merges two dictionaries. Already present elements are override.

Syntax: dictionary1.update(dictionary2)

Example: >>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }

                  >>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }

                  >>> marks1.update(marks2)

                  >>> marks1 {'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}

             

: PRACTICE EXERCISE ON A DICTIONARY:

Q1: Program to traversing a dictionary

dict1={1:”Apple”,2:”Banana”,3:”Orange”,

            4:”Grapes”}

 for i in dict1:

     print(I,”:”,dict1[i])

******************************************

Q2: Write a  Python program to iterate over dictionaries using for loops.

d = {'x': 10, 'y': 20, 'z': 30}

for i, j in d.items():

    print(i, '->', j)

Q3: Program to append and update the dictionary

dict1={"Name":"Aman","Class":"O Level","Year":2024}

print(dict1)

dict1["Stream"]="CS"

print(dict1)

dict1.update({"Stream":"Math"})

print(dict1)

Q4: Write a python program to find the frequency of all elements in a given dictionary

dict1 = {'id': 102, 'Name': "jai", 'class': "cs", 'year': 2025, 'marks': 102}

freq = {}

for i in dict1.values():

    if i in freq:

        freq[i] += 1

    else:

        freq[i] = 1

print("Frequency of each element in the dictionary values:")

for key, val in freq.items():

    print(key,":" ,val)

Q5: write a python program to short  Key and value of a dictionary

dict1={"uma":76,"Mohan":85,"Beena":92,

              "Lisa":28}

for i in sorted(dict1):

         print(i,"is",dict1[i],"Year Old")

#########################

dict1={"uma":76,"Mohan":85,"Beena":92,"

              Lisa":28}

for i in sorted(dict1,key=dict1.get):

         print(i,"is",dict1[i],"Year Old")

Q6: Write program to Use the get method to print the value of the "model" key of the car dictionary.

car ={  "brand": "Ford",  "model": "Figo",

             "year": 1964 }

print(car.get("model"))

Q7: Write program to Change the "year" value

         from 1964 to 2020.

car =   {  "brand": "Ford",  "model": "Figo",

              "year": 1964}

car["year"] = 2020

print(car)

Q8:Add the key/value pair "color" : "red" to the car dictionary.

car =   {  "brand": "Ford",  "model":  "Figo",

             "year": 1964}

car["color"]="red"

print(car)

Q9: Write program to Use the pop method to

       remove "model" from the car dictionary.

car =   { "brand": "Ford",  "model":  "Figo",

             "year": 1964}

car.pop("model")

print(car)

Q10: Write program to Use the clear method to empty the car dictionary.

car =   {"brand": "Ford", "model": "Mustang",

            "year": 1964}

car.clear()

print(car)

Q11: Write a Python program to add a key to a dictionary.

dict1 = {0: 10, 1: 20}

print(dict1)

dict1.update({2: 30})

Q12: Write a Program to enter and display information in a dictionary

rec=dict()

num=int(input(" Enter the number of students:"))

i=1

while( i<=num):

    name=input("Enter the Name of student:")

    per=input("Enter the marks % of student:")

    rec[name]=per

    i=i+1

print("\t","Name","\t","% Marks")

for i in rec:

    print("\t",i,"\t\t",rec[i])

Q13: Write a Program to enter name and percentage of marks in a dictionary and then display information according to marks percentage i.e value based.

rec=dict()

num=int(input(" Enter the number of students:"))

i=1

while( i<=num):

    name=input("Enter the Name of student:")

    per=input("Enter the marks % of student:")

    rec[name]=per

    i=i+1

    a=rec.keys()

print("\t","Name","\t\t","% Marks")

for i in sorted(a,key=rec.get):

    print("\t",i,"\t\t",rec[i])

Q14: Write a  Python script to concatenate the following dictionaries to create a new one.

dic1 = {1: 10, 2: 20}

dic2 = {3: 30, 4: 40}

dic3 = {5: 50, 6: 60}

dic4 = {}

for i in (dic1, dic2, dic3):

    dic4.update(i)

print(dic4)

Q15: Write a  Python program to check whether a given key already exists in a dictionary.

d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

x=int(input("plz enter the key name to check"))

if x in d:

    print('Key is present in dictionary')

else:

    print('Key is not present in dict')

Q16: Write  a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).

n = int(input("Input a number "))

d = dict()

for x in range(1, n + 1):

    d[x] = x * x

print(d)

Q17: Write a  Python script to merge two  Python dictionaries.

d1 = {'a': 100, 'b': 200}

d2 = {'x': 300, 'y': 200}

d1.update(d2)

print(d1)

********************************

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}

dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict3 = dict1.copy()

dict3.update(dict2)

print(dict3)

Q18:Write a Python program to sum all the items in a dictionary.

dict1 = {'data1': 100, 'data2': -54, 'data3': 247}

result = sum(dict1.values())

print(result)

Q19:Write a  Python program to remove a key from a dictionary

dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

print(dict)

if 'a' in dict:

    del dict['a']

print(dict)

Q20: Write a  Python program to map two lists into a dictionary.

keys = [1, 2, 3]

values = ['red', 'green', 'blue']

dict1 = dict(zip(keys, values))

print(dict1)

Q21:Write a  Python program to sort a given

             dictionary by key

dict1 = { 'red': '#FF0000', 'green': '#008000',

             'black': '#000000', 'white': '#FFFFFF' }

for key in sorted(dict1):

    print("%s: %s" % (key, dict1 [key]))

Q22:Write a  Python program to combine two dictionary by adding values for common keys.

from collections import Counter

d1 = {'a': 100, 'b': 200, 'c': 300}

d2 = {'a': 300, 'b': 200, 'd': 400}

d = Counter(d1) + Counter(d2)

print(d)

Q22:Write a  Python program to Convert two lists into a dictionary

Use the zip(keys, values) to aggregate two lists.

Wrap the result of a zip() function into a dict() constructor.

keys = ['Ten', 'Twenty', 'Thirty']

values = [10, 20, 30]

res_dict = dict(zip(keys, values))

print(res_dict)

Q22:Write a  Python program to Convert two lists into a dictionary

  • Using a loop and update() method of a dictionary

keys = ['Ten', 'Twenty', 'Thirty']

values = [10, 20, 30]

dict1 = dict()  # empty dictionary

for i in range(len(keys)):

    dict1.update({keys[i]: values[i]})

print(dict1)

Q23:Write a  Python program to Delete a list of keys from a dictionary

dict1 = {"name": "Kelly",  "age": 25,

              "salary": 8000, "city": "New york" }

# Keys to remove

keys = ["name", "salary"]

for k in keys:

    dict1.pop(k)

print(dict1)

Q24:Write a  Python program to Convert two lists into a dictionary Rename key of a dictionary

dict1 = { "name": "Kelly", "age": 25,

    "salary": 8000,  "city": "New york" }

dict1['location'] = dict1.pop('city')

print(dict1)

Q25:Write a  Python program to Get the key of a minimum value from the following dictionary

dict1 = { 'Physics': 82, 'Math': 65, 'history': 75}

print(min(dict1, key=dict1.get))

Q26:Write a Python program to change Brad’s salary to 8500 in the following dictionary.

dict1 = {'emp1': {'name': 'Jhon', 'salary': 7500},

            'emp2': {'name': 'Emma', 'salary': 8000},

            'emp3': {'name': 'Brad', 'salary': 6500}}

dict1['emp3']['salary'] = 8500

print(dict1)

Q27:Write a  Python program to Get the key of a maximum value from the following dictionary

dict1 = { 'Physics': 82,'Math': 65,'history': 75}

print(max(dict1, key=dict1.get))