Q-1.Write a Python program to remove duplicates from Dictionary.
Input: student_data ={'rollno_1':{'name': 'Sara' ,'class': 'V', 'subjects': ['english, math, science']},
'rollno_2':{'name':'David', 'class': 'V', 'subjects': ['english, math, science']},
'rollno_3':{'name':'Sara', 'class': 'V', 'subjects': ['english, math, science']},
'rollno_4':{'name':'Surya', 'class': 'V', 'subjects': ['english, math,   science']},}
Output:{'rollno_1': {'name': 'Sara', 'class': 'V', 'subjects': ['english, math, science']}, 'rollno_2': {'name': 'David', 'class': 'V', 'subjects': ['english, math, science']}, 'rollno_4': {'name': 'Surya', 'class': 'V', 'subjects': ['english, math, science']}}

Python Code:

# Remove duplicates 

student_data ={'rollno_1':{'name': 'Sara' ,'class': 'V', 'subjects': ['english, math, science']},
 'rollno_2':{'name':'David', 'class': 'V', 'subjects': ['english, math, science']},
 'rollno_3':{'name':'Sara', 'class': 'V', 'subjects': ['english, math, science']},
 'rollno_4':{'name':'Surya', 'class': 'V', 'subjects': ['english, math, science']},
}

result = {}
for key , value in student_data.items():
    if value not in result.values():
        result[key] = value
print(result)
Q-2.Write a Python Program to Count words in a String using Dictionary.
Input: Please enter any String : Delhi Delhi Noida Delhi Gurgaon Noida
Output: Dictionary Items : {'Delhi': 3, 'Noida': 2, 'Gurgaon': 1}

Python Code:

# Count words in a String using Dictionary

string = input("Please enter any String : ")
words = []

words = string.split()
frequency = [words.count(i) for i in words]

my_Dict = dict(zip(words, frequency))
print("Dictionary Items  :  ",  my_Dict)
Q-3.Write a Python program to remove a key from a dictionary.
Input: my_dict={'a':1,'b':2,'c':3,'d':4,'e':5}
Output: dictionary after deletion: {'b': 2, 'c': 3, 'd': 4, 'e': 5}

Python Code:

#remove a key

my_dict={'a':1,'b':2,'c':3,'d':4,'e':5}
print(my_dict)
if 'a' in my_dict:
    del my_dict['a']
print("dictionary after deletion:", my_dict)
Q-4.Write a Python program to count characters in string using dictionary.
Input: str1 = 'data-stats'
Output: {'d': 1, 'a': 3, 't': 3, '-': 1, 's': 2}

Python Code:

#count characters in string 

str1 = 'data-stats' 
my_dict = {}
for key in str1:
    my_dict[key] = my_dict.get(key, 0) + 1
print(my_dict)
Q-5.Write a Python program to find the depth of dictionary.
Input: dic = {1:'datastats', 2: {3: {4: {}}}}
Output: 4 (depth of dic)

Python Code:

# find the depth of dictionary

def dict_depth(dic): 
    str_dic = str(dic) 
    counter = 0
    for i in str_dic: 
        if i == "{": 
            counter += 1
    return(counter) 
dic = {1:'datastats', 2: {3: {4: {}}}} 
print(dict_depth(dic)

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert