Python Devlopment






Operations in Dictionary



Followings are the operations in dictonary

1. Traversing

2. Membership

 

1. Traversing

Traversing in a dictonary is done on the basis of keys. For this, for-loop is used,which iterates over the keys in the dictonary and prints the corresponding values using keys.

Example-01: Printing only keys

dict={1: 'Red', 2: 'Yellow' , 3: 'Green'}

for i in dict:
    print(i)

#Output
1
2
3

 

Example-02: Printing only values

dict={1: 'Red', 2: 'Yellow' , 3: 'Green'}

for i in dict:
    print(dict[i])

#Output
Red
Yellow
Green

 

Example-03: Printing key-value pairs

dict={1: 'Red', 2: 'Yellow' , 3: 'Green'}

for i in dict:
    print(i, dict[i])

#Output
1 Red
2 Yellow
3 Green

 

2. Membership

Using the membership operator ( in and not in), we can test whether a key in the dicctonary is present or not. We have seen the in operator earlier as ell in the list and the tuple. It takes an input key and finds the key in the dictonary. If the key is found, then it returns True, otherwise, False.

>>>cubes={1:1,2:8,3:27,4:64,5:125,6:216}
>>> 3 in cubes
True         #Output

>>>7 not in cubes
True         #Output

>>>10 in cubes
False        #Output

 

Lab Assignments:

1. Given an integer number n, write a program to generate a dictionary that contains (i,i*i) such that is an integer number between 1 and n(both included). The program should then print the dictionary. (Hint: Suppose,  input is supplied to the program: 6, then output should be: {1:1, 2:4, 3:9, 4:16, 5:25, 6:36}

n=int(input("Enter Number : "))
d=dict()
for i in range(1,n+1):
    d[i]=i*i

print(d)

#Output
Enter Number : 6
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}

 

2. Define a function that prints a dictionary where the keys are numbers between 1 and 4 (both included) and the values are cubes of the keys.

n=int(input("Enter Number : "))
d=dict()

for i in range(1,n+1):
    d[i]=i**3
print(d)

#Output
Enter Number : 6
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}

 

3. Write a Python program to count the frequency of characters using the get() method.

def freq_character(f):
    D=dict()
    for i in f:
        if i not in D:
            D[i]=1
        else:
            D[i]=D.get(i,0)+1

    return(D)

D=freq_character("APPLE")
print(D)

#Output
{'A': 1, 'P': 2, 'L': 1, 'E': 1}