Python Dictonary Programs

Q.1)

Code:

dictionary = {'MSBTE':'Maharashtra State Board of Technical Education',

              'CO':'Computer Engineering',

              'SEM':'Sixth'

              }

del dictionary['CO'];

for key, values in dictionary.items():

    print(key)

dictionary.clear();

for key, values in dictionary.items():

    print(key)

del dictionary;

for key, values in dictionary.items():

    print(key)

 

Output:


 

Q.2)

Code:

dictionary1 = {'Google':1,

              'Facebook':2,

              'Microsoft':3

              }

dictionary2 = {'GFG':1,

              'Microsoft':2,

              'Youtube':3

              }

dictionary1.update(dictionary2);

for key, values in dictionary1.items():

    print(key, values)

 

Output:

 

Q.3)

Code:

temp = dict()

temp['key1'] = {'key1' : 44, 'key2' : 566}

temp['key2'] = [1,2,3,4]

for (key,values) in temp.items():

    print(values, end="")

 

Output:


 

Q. Program to sort a dictionary by value.

 

Code:

 

y={'Zainab':40,'Rayyan':2,'Ata':1,'Asim':3, 'Ahmed':11}

l=list(y.items())

l.sort()           

print('Ascending order is',l)

l=list(y.items())

l.sort(reverse=True)

print('Descending order is',l)

dict=dict(l)

print("Dictionary",dict)

 

Output:

 

Q. Program to concatenate following dictionaries to create a new one.

 

Code:

dic1 = {1:10, 2:20}

dic2 = {3:30, 4:40}

dic3 = {5:50, 6:60}

print("Dic1:", dic1)

print("Dic2:", dic2)

print("Dic3:", dic3)

dic1.update(dic2)

dic1.update(dic3)

print("Concatenated Dictionary:", dic1)

Output:


 

Q. Program to combine two dictionary adding values for common keys.

 

Code:

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

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

print("Dict1:", d1);

print("Dict1:", d2);

for key in d2:

    if key in d1:

        d2[key] = d2[key] + d1[key]

    else:

        pass

print("Adding common values:",d2)

 

Output:

 

Q. Program to combine two dictionary adding values for common keys.

 

Code:

d1 = [{'V' : "S001"}, {'V' : "S002"}, {'VI' : "S001"}, {'VI' : "S005"}, {'VII' : "S005"}, {"V" : "S009"}, {"VIII" : "S007"}]

print("The original:" + str(d1))

res = list(set(val for dic in d1 for val in dic.values()))

print("The unique values are:" + str(res));

 

Output:


 

Q. Program to find the highest 3 values in a dictionary.

 

Code:

from collections import Counter

my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69}

k = Counter(my_dict)

high = k.most_common(3)

print("Initial Dictionary:",my_dict)

print("Dictionary with 3 highest values:")

print("Keys: Values")

for i in high:

            print(i[0]," :",i[1]," ")

Output:


Comments

Popular posts from this blog

State use of pep and pip