Description
stringlengths
9
105
Link
stringlengths
45
135
Code
stringlengths
10
26.8k
Test_Case
stringlengths
9
202
Merge
stringlengths
63
27k
Python dictionary with keys having multiple inputs
https://www.geeksforgeeks.org/python-dictionary-with-keys-having-multiple-inputs/
# Creating a dictionary with multiple inputs for keys data = { (1, "John", "Doe"): {"a": "geeks", "b": "software", "c": 75000}, (2, "Jane", "Smith"): {"e": 30, "f": "for", "g": 90000}, (3, "Bob", "Johnson"): {"h": 35, "i": "project", "j": "geeks"}, (4, "Alice", "Lee"): {"k": 40, "l": "marketing", "m": 100000}, } # Accessing the values using the keys print(data[(1, "John", "Doe")]["a"]) print(data[(2, "Jane", "Smith")]["f"]) print(data[(3, "Bob", "Johnson")]["j"]) data[(1, "John", "Doe")]["a"] = {"b": "marketing", "c": 75000} data[(3, "Bob", "Johnson")]["j"] = {"h": 35, "i": "project"} print(data[(1, "John", "Doe")]["a"]) print(data[(3, "Bob", "Johnson")]["j"])
#Output : {(10, 20, 30): 0, (5, 2, 4): 3}
Python dictionary with keys having multiple inputs # Creating a dictionary with multiple inputs for keys data = { (1, "John", "Doe"): {"a": "geeks", "b": "software", "c": 75000}, (2, "Jane", "Smith"): {"e": 30, "f": "for", "g": 90000}, (3, "Bob", "Johnson"): {"h": 35, "i": "project", "j": "geeks"}, (4, "Alice", "Lee"): {"k": 40, "l": "marketing", "m": 100000}, } # Accessing the values using the keys print(data[(1, "John", "Doe")]["a"]) print(data[(2, "Jane", "Smith")]["f"]) print(data[(3, "Bob", "Johnson")]["j"]) data[(1, "John", "Doe")]["a"] = {"b": "marketing", "c": 75000} data[(3, "Bob", "Johnson")]["j"] = {"h": 35, "i": "project"} print(data[(1, "John", "Doe")]["a"]) print(data[(3, "Bob", "Johnson")]["j"]) #Output : {(10, 20, 30): 0, (5, 2, 4): 3} [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
# Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(myDict): list = [] for i in myDict: list.append(myDict[i]) final = sum(list) return final # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict))
#Output : Sum : 600
Python program to find the sum of all items in a dictionary # Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(myDict): list = [] for i in myDict: list.append(myDict[i]) final = sum(list) return final # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
# Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): sum = 0 for i in dict.values(): sum = sum + i return sum # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict))
#Output : Sum : 600
Python program to find the sum of all items in a dictionary # Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): sum = 0 for i in dict.values(): sum = sum + i return sum # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
# Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): sum = 0 for i in dict: sum = sum + dict[i] return sum # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict))
#Output : Sum : 600
Python program to find the sum of all items in a dictionary # Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): sum = 0 for i in dict: sum = sum + dict[i] return sum # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
# Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): return sum(dict.values()) # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict))
#Output : Sum : 600
Python program to find the sum of all items in a dictionary # Python3 Program to find sum of # all items in a Dictionary # Function to print sum def returnSum(dict): return sum(dict.values()) # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
import functools dic = {"a": 100, "b": 200, "c": 300} sum_dic = functools.reduce(lambda ac, k: ac + dic[k], dic, 0) print("Sum :", sum_dic)
#Output : Sum : 600
Python program to find the sum of all items in a dictionary import functools dic = {"a": 100, "b": 200, "c": 300} sum_dic = functools.reduce(lambda ac, k: ac + dic[k], dic, 0) print("Sum :", sum_dic) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
def returnSum(myDict): return sum(myDict[key] for key in myDict) dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : Sum : 600
Python program to find the sum of all items in a dictionary def returnSum(myDict): return sum(myDict[key] for key in myDict) dict = {"a": 100, "b": 200, "c": 300} print("Sum :", returnSum(dict)) # This code is contributed by Edula Vinay Kumar Reddy #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
import functools def sum_dict_values(dict): return functools.reduce(lambda acc, x: acc + dict[x], dict, 0) # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", sum_dict_values(dict))
#Output : Sum : 600
Python program to find the sum of all items in a dictionary import functools def sum_dict_values(dict): return functools.reduce(lambda acc, x: acc + dict[x], dict, 0) # Driver Function dict = {"a": 100, "b": 200, "c": 300} print("Sum :", sum_dict_values(dict)) #Output : Sum : 600 [END]
Python program to find the sum of all items in a dictionary
https://www.geeksforgeeks.org/python-program-to-find-the-sum-of-all-items-in-a-dictionary/
import numpy as np # function to return sum def returnSum(dict): # convert dict values to a NumPy array values = np.array(list(dict.values())) # return the sum of the values return np.sum(values) # driver code dict = {"a": 100, "b": 200, "c": 300} print("Sum:", returnSum(dict)) # this code is contributed by Jyothi pinjala.
#Output : Sum : 600
Python program to find the sum of all items in a dictionary import numpy as np # function to return sum def returnSum(dict): # convert dict values to a NumPy array values = np.array(list(dict.values())) # return the sum of the values return np.sum(values) # driver code dict = {"a": 100, "b": 200, "c": 300} print("Sum:", returnSum(dict)) # this code is contributed by Jyothi pinjala. #Output : Sum : 600 [END]
Python program to find the size of a Dictionary in python
https://www.geeksforgeeks.org/find-the-size-of-a-dictionary-in-python/
import sys # sample Dictionaries dic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"} dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionaries print("Size of dic1: " + str(sys.getsizeof(dic1)) + "bytes") print("Size of dic2: " + str(sys.getsizeof(dic2)) + "bytes") print("Size of dic3: " + str(sys.getsizeof(dic3)) + "bytes")
#Output : Size of dic1: 216bytes
Python program to find the size of a Dictionary in python import sys # sample Dictionaries dic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"} dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionaries print("Size of dic1: " + str(sys.getsizeof(dic1)) + "bytes") print("Size of dic2: " + str(sys.getsizeof(dic2)) + "bytes") print("Size of dic3: " + str(sys.getsizeof(dic3)) + "bytes") #Output : Size of dic1: 216bytes [END]
Python program to find the size of a Dictionary in python
https://www.geeksforgeeks.org/find-the-size-of-a-dictionary-in-python/
# sample Dictionaries dic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"} dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionaries print("Size of dic1: " + str(dic1.__sizeof__()) + "bytes") print("Size of dic2: " + str(dic2.__sizeof__()) + "bytes") print("Size of dic3: " + str(dic3.__sizeof__()) + "bytes")
#Output : Size of dic1: 216bytes
Python program to find the size of a Dictionary in python # sample Dictionaries dic1 = {"A": 1, "B": 2, "C": 3} dic2 = {"Geek1": "Raju", "Geek2": "Nikhil", "Geek3": "Deepanshu"} dic3 = {1: "Lion", 2: "Tiger", 3: "Fox", 4: "Wolf"} # print the sizes of sample Dictionaries print("Size of dic1: " + str(dic1.__sizeof__()) + "bytes") print("Size of dic2: " + str(dic2.__sizeof__()) + "bytes") print("Size of dic3: " + str(dic3.__sizeof__()) + "bytes") #Output : Size of dic1: 216bytes [END]
Ways to sort list of dictionaries by values in Python - Using itemgetter
https://www.geeksforgeeks.org/ways-sort-list-dictionaries-values-python-using-itemgetter/
# Python code demonstrate the working of sorted()# and itemgetter??????# import"operator" for implementing itemgetterfrom operator import itemgetter??????# Initializing list of dictionarieslist "name": "Nandini", "age": 20},???????????????"name": "Manjeet", "age": 20},???????????????"name": "Nikhil", "age": 19}]??????# using sorted and itemgetter to print list sorted by agepr"The list printed sorting by age: "print sorted(list, key=itemgetter('age'))??????pr"\r")??????# using sorted and itemgetter to print# list sorted by both age and name# notice t"Manjeet" now comes before "Nandini"print "The list printed sorting by age and name: "print sorted(list, key=itemgetter('age', 'name'))??????pr"\r")??????# using sorted and itemgetter to print list# sorted by age in descending orderpr"The list printed sorting by age in descending order: "print sorted(list, key=itemgetter('age'), reverse=True)
#Output : The list printed sorting by age:
Ways to sort list of dictionaries by values in Python - Using itemgetter # Python code demonstrate the working of sorted()# and itemgetter??????# import"operator" for implementing itemgetterfrom operator import itemgetter??????# Initializing list of dictionarieslist "name": "Nandini", "age": 20},???????????????"name": "Manjeet", "age": 20},???????????????"name": "Nikhil", "age": 19}]??????# using sorted and itemgetter to print list sorted by agepr"The list printed sorting by age: "print sorted(list, key=itemgetter('age'))??????pr"\r")??????# using sorted and itemgetter to print# list sorted by both age and name# notice t"Manjeet" now comes before "Nandini"print "The list printed sorting by age and name: "print sorted(list, key=itemgetter('age', 'name'))??????pr"\r")??????# using sorted and itemgetter to print list# sorted by age in descending orderpr"The list printed sorting by age in descending order: "print sorted(list, key=itemgetter('age'), reverse=True) #Output : The list printed sorting by age: [END]
Ways to sort list of dictionaries by values in Python - Using lambda function
https://www.geeksforgeeks.org/ways-sort-list-dictionaries-values-python-using-lambda-function/
# Python code demonstrate the working of # sorted() with lambda # Initializing list of dictionaries list = [ {"name": "Nandini", "age": 20}, {"name": "Manjeet", "age": 20}, {"name": "Nikhil", "age": 19}, ] # using sorted and lambda to print list sorted # by age print("The list printed sorting by age: ") print(sorted(list, key=lambda i: i["age"])) print("\r") # using sorted and lambda to print list sorted # by both age and name. Notice that "Manjeet" # now comes before "Nandini" print("The list printed sorting by age and name: ") print(sorted(list, key=lambda i: (i["age"], i["name"]))) print("\r") # using sorted and lambda to print list sorted # by age in descending order print("The list printed sorting by age in descending order: ") print(sorted(list, key=lambda i: i["age"], reverse=True))
#Output : The list printed sorting by age:
Ways to sort list of dictionaries by values in Python - Using lambda function # Python code demonstrate the working of # sorted() with lambda # Initializing list of dictionaries list = [ {"name": "Nandini", "age": 20}, {"name": "Manjeet", "age": 20}, {"name": "Nikhil", "age": 19}, ] # using sorted and lambda to print list sorted # by age print("The list printed sorting by age: ") print(sorted(list, key=lambda i: i["age"])) print("\r") # using sorted and lambda to print list sorted # by both age and name. Notice that "Manjeet" # now comes before "Nandini" print("The list printed sorting by age and name: ") print(sorted(list, key=lambda i: (i["age"], i["name"]))) print("\r") # using sorted and lambda to print list sorted # by age in descending order print("The list printed sorting by age in descending order: ") print(sorted(list, key=lambda i: i["age"], reverse=True)) #Output : The list printed sorting by age: [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
# Python code to merge dict using update() method def Merge(dict1, dict2): return dict2.update(dict1) # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} # This returns None print(Merge(dict1, dict2)) # changes made in dict2 print(dict2)
#Output : None
Python | Merging two Dictionaries # Python code to merge dict using update() method def Merge(dict1, dict2): return dict2.update(dict1) # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} # This returns None print(Merge(dict1, dict2)) # changes made in dict2 print(dict2) #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
# Python code to merge dict using a single # expression def Merge(dict1, dict2): res = {**dict1, **dict2} return res # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} dict3 = Merge(dict1, dict2) print(dict3)
#Output : None
Python | Merging two Dictionaries # Python code to merge dict using a single # expression def Merge(dict1, dict2): res = {**dict1, **dict2} return res # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} dict3 = Merge(dict1, dict2) print(dict3) #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
# code # Python code to merge dict using a single # expression def Merge(dict1, dict2): res = dict1 | dict2 return res # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by virentanti16
#Output : None
Python | Merging two Dictionaries # code # Python code to merge dict using a single # expression def Merge(dict1, dict2): res = dict1 | dict2 return res # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by virentanti16 #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
# code # Python code to merge dictionary def Merge(dict1, dict2): for i in dict2.keys(): dict1[i] = dict2[i] return dict1 # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by Bhavya Koganti
#Output : None
Python | Merging two Dictionaries # code # Python code to merge dictionary def Merge(dict1, dict2): for i in dict2.keys(): dict1[i] = dict2[i] return dict1 # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} dict3 = Merge(dict1, dict2) print(dict3) # This code is contributed by Bhavya Koganti #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
from collections import ChainMap # create the dictionaries to be merged dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} # create a ChainMap with the dictionaries as elements merged_dict = ChainMap(dict1, dict2) # access and modify elements in the merged dictionary print(merged_dict["a"]) # prints 1 print(merged_dict["c"]) # prints 3 merged_dict["c"] = 5 # updates value in dict2 print(merged_dict["c"]) # prints 5 # add a new key-value pair to the merged dictionary merged_dict["e"] = 6 # updates dict1 print(merged_dict["e"]) # prints 6
#Output : None
Python | Merging two Dictionaries from collections import ChainMap # create the dictionaries to be merged dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} # create a ChainMap with the dictionaries as elements merged_dict = ChainMap(dict1, dict2) # access and modify elements in the merged dictionary print(merged_dict["a"]) # prints 1 print(merged_dict["c"]) # prints 3 merged_dict["c"] = 5 # updates value in dict2 print(merged_dict["c"]) # prints 5 # add a new key-value pair to the merged dictionary merged_dict["e"] = 6 # updates dict1 print(merged_dict["e"]) # prints 6 #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} print(merge_dictionaries(dict1, dict2))
#Output : None
Python | Merging two Dictionaries def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict # Driver code dict1 = {"x": 10, "y": 8} dict2 = {"a": 6, "b": 4} print(merge_dictionaries(dict1, dict2)) #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
# method to merge two dictionaries using the dict() constructor with the union operator (|) def Merge(dict1, dict2): # create a new dictionary by merging the items of the two dictionaries using the union operator (|) merged_dict = dict(dict1.items() | dict2.items()) # return the merged dictionary return merged_dict # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} # merge the two dictionaries using the Merge() function merged_dict = Merge(dict1, dict2) # print the merged dictionary print(merged_dict)
#Output : None
Python | Merging two Dictionaries # method to merge two dictionaries using the dict() constructor with the union operator (|) def Merge(dict1, dict2): # create a new dictionary by merging the items of the two dictionaries using the union operator (|) merged_dict = dict(dict1.items() | dict2.items()) # return the merged dictionary return merged_dict # Driver code dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} # merge the two dictionaries using the Merge() function merged_dict = Merge(dict1, dict2) # print the merged dictionary print(merged_dict) #Output : None [END]
Python | Merging two Dictionaries
https://www.geeksforgeeks.org/python-merging-two-dictionaries/
from functools import reduce def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} dict_list = [dict1, dict2] # Put the dictionaries into a list result_dict = reduce(merge_dictionaries, dict_list) print(result_dict) # This code is contributed by Rayudu.
#Output : None
Python | Merging two Dictionaries from functools import reduce def merge_dictionaries(dict1, dict2): merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict dict1 = {"a": 10, "b": 8} dict2 = {"d": 6, "c": 4} dict_list = [dict1, dict2] # Put the dictionaries into a list result_dict = reduce(merge_dictionaries, dict_list) print(result_dict) # This code is contributed by Rayudu. #Output : None [END]
Program to create grade calculator in Python
https://www.geeksforgeeks.org/program-create-grade-calculator-in-python/
print("Enter Marks Obtained in 5 Subjects: ") total1 = 44 total2 = 67 total3 = 76 total4 = 99 total5 = 58 tot = total1 + total2 + total3 + total4 + total4 avg = tot / 5 if avg >= 91 and avg <= 100: print("Your Grade is A1") elif avg >= 81 and avg < 91: print("Your Grade is A2") elif avg >= 71 and avg < 81: print("Your Grade is B1") elif avg >= 61 and avg < 71: print("Your Grade is B2") elif avg >= 51 and avg < 61: print("Your Grade is C1") elif avg >= 41 and avg < 51: print("Your Grade is C2") elif avg >= 33 and avg < 41: print("Your Grade is D") elif avg >= 21 and avg < 33: print("Your Grade is E1") elif avg >= 0 and avg < 21: print("Your Grade is E2") else: print("Invalid Input!")
#Output : 10% of marks scored from submission of Assignments
Program to create grade calculator in Python print("Enter Marks Obtained in 5 Subjects: ") total1 = 44 total2 = 67 total3 = 76 total4 = 99 total5 = 58 tot = total1 + total2 + total3 + total4 + total4 avg = tot / 5 if avg >= 91 and avg <= 100: print("Your Grade is A1") elif avg >= 81 and avg < 91: print("Your Grade is A2") elif avg >= 71 and avg < 81: print("Your Grade is B1") elif avg >= 61 and avg < 71: print("Your Grade is B2") elif avg >= 51 and avg < 61: print("Your Grade is C1") elif avg >= 41 and avg < 51: print("Your Grade is C2") elif avg >= 33 and avg < 41: print("Your Grade is D") elif avg >= 21 and avg < 33: print("Your Grade is E1") elif avg >= 0 and avg < 21: print("Your Grade is E2") else: print("Invalid Input!") #Output : 10% of marks scored from submission of Assignments [END]
Program to create grade calculator in Python
https://www.geeksforgeeks.org/program-create-grade-calculator-in-python/
# Creating a dictionary which # consists of the student name, # assignment result test results # and their respective lab results # 1. Jack's dictionary jack = { "name": "Jack Frost", "assignment": [80, 50, 40, 20], "test": [75, 75], "lab": [78.20, 77.20], } # 2. James's dictionary james = { "name": "James Potter", "assignment": [82, 56, 44, 30], "test": [80, 80], "lab": [67.90, 78.72], } # 3. Dylan's dictionary dylan = { "name": "Dylan Rhodes", "assignment": [77, 82, 23, 39], "test": [78, 77], "lab": [80, 80], } # 4. Jessica's dictionary jess = { "name": "Jessica Stone", "assignment": [67, 55, 77, 21], "test": [40, 50], "lab": [69, 44.56], } # 5. Tom's dictionary tom = { "name": "Tom Hanks", "assignment": [29, 89, 60, 56], "test": [65, 56], "lab": [50, 40.6], } # Function calculates average def get_average(marks): total_sum = sum(marks) total_sum = float(total_sum) return total_sum / len(marks) # Function calculates total average def calculate_total_average(students): assignment = get_average(students["assignment"]) test = get_average(students["test"]) lab = get_average(students["lab"]) # Return the result based # on weightage supplied # 10 % from assignments # 70 % from test # 20 % from lab-works return 0.1 * assignment + 0.7 * test + 0.2 * lab # Calculate letter grade of each student def assign_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "E" # Function to calculate the total # average marks of the whole class def class_average_is(student_list): result_list = [] for student in student_list: stud_avg = calculate_total_average(student) result_list.append(stud_avg) return get_average(result_list) # Student list consisting the # dictionary of all students students = [jack, james, dylan, jess, tom] # Iterate through the students list # and calculate their respective # average marks and letter grade for i in students: print(i["name"]) print("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=") print("Average marks of %s is : %s " % (i["name"], calculate_total_average(i))) print( "Letter Grade of %s is : %s" % (i["name"], assign_letter_grade(calculate_total_average(i))) ) print() # Calculate the average of whole class class_av = class_average_is(students) print("Class Average is %s" % (class_av)) print("Letter Grade of the class is %s " % (assign_letter_grade(class_av)))
#Output : 10% of marks scored from submission of Assignments
Program to create grade calculator in Python # Creating a dictionary which # consists of the student name, # assignment result test results # and their respective lab results # 1. Jack's dictionary jack = { "name": "Jack Frost", "assignment": [80, 50, 40, 20], "test": [75, 75], "lab": [78.20, 77.20], } # 2. James's dictionary james = { "name": "James Potter", "assignment": [82, 56, 44, 30], "test": [80, 80], "lab": [67.90, 78.72], } # 3. Dylan's dictionary dylan = { "name": "Dylan Rhodes", "assignment": [77, 82, 23, 39], "test": [78, 77], "lab": [80, 80], } # 4. Jessica's dictionary jess = { "name": "Jessica Stone", "assignment": [67, 55, 77, 21], "test": [40, 50], "lab": [69, 44.56], } # 5. Tom's dictionary tom = { "name": "Tom Hanks", "assignment": [29, 89, 60, 56], "test": [65, 56], "lab": [50, 40.6], } # Function calculates average def get_average(marks): total_sum = sum(marks) total_sum = float(total_sum) return total_sum / len(marks) # Function calculates total average def calculate_total_average(students): assignment = get_average(students["assignment"]) test = get_average(students["test"]) lab = get_average(students["lab"]) # Return the result based # on weightage supplied # 10 % from assignments # 70 % from test # 20 % from lab-works return 0.1 * assignment + 0.7 * test + 0.2 * lab # Calculate letter grade of each student def assign_letter_grade(score): if score >= 90: return "A" elif score >= 80: return "B" elif score >= 70: return "C" elif score >= 60: return "D" else: return "E" # Function to calculate the total # average marks of the whole class def class_average_is(student_list): result_list = [] for student in student_list: stud_avg = calculate_total_average(student) result_list.append(stud_avg) return get_average(result_list) # Student list consisting the # dictionary of all students students = [jack, james, dylan, jess, tom] # Iterate through the students list # and calculate their respective # average marks and letter grade for i in students: print(i["name"]) print("=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=") print("Average marks of %s is : %s " % (i["name"], calculate_total_average(i))) print( "Letter Grade of %s is : %s" % (i["name"], assign_letter_grade(calculate_total_average(i))) ) print() # Calculate the average of whole class class_av = class_average_is(students) print("Class Average is %s" % (class_av)) print("Letter Grade of the class is %s " % (assign_letter_grade(class_av))) #Output : 10% of marks scored from submission of Assignments [END]
Python - Insertion at the beginning in Ordereddicteddict
https://www.geeksforgeeks.org/python-insertion-at-the-beginning-in-ordereddict/?ref=leftbar-rightbar
# Python code to demonstrate # insertion of items in beginning of ordered dict from collections import OrderedDict # initialising ordered_dict iniordered_dict = OrderedDict([("akshat", "1"), ("nikhil", "2")]) # inserting items in starting of dict iniordered_dict.update({"manjeet": "3"}) iniordered_dict.move_to_end("manjeet", last=False) # print result print("Resultant Dictionary : " + str(iniordered_dict))
Input: original_dict = {'a':1, 'b':2}
Python - Insertion at the beginning in Ordereddicteddict # Python code to demonstrate # insertion of items in beginning of ordered dict from collections import OrderedDict # initialising ordered_dict iniordered_dict = OrderedDict([("akshat", "1"), ("nikhil", "2")]) # inserting items in starting of dict iniordered_dict.update({"manjeet": "3"}) iniordered_dict.move_to_end("manjeet", last=False) # print result print("Resultant Dictionary : " + str(iniordered_dict)) Input: original_dict = {'a':1, 'b':2} [END]
Python - Insertion at the beginning in Ordereddicteddict
https://www.geeksforgeeks.org/python-insertion-at-the-beginning-in-ordereddict/?ref=leftbar-rightbar
# Python code to demonstrate # insertion of items in beginning of ordered dict from collections import OrderedDict # initialising ordered_dict ini_dict1 = OrderedDict([("akshat", "1"), ("nikhil", "2")]) ini_dict2 = OrderedDict([("manjeet", "4"), ("akash", "4")]) # adding in beginning of dict both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items())) # print result print("Resultant Dictionary :" + str(both))
Input: original_dict = {'a':1, 'b':2}
Python - Insertion at the beginning in Ordereddicteddict # Python code to demonstrate # insertion of items in beginning of ordered dict from collections import OrderedDict # initialising ordered_dict ini_dict1 = OrderedDict([("akshat", "1"), ("nikhil", "2")]) ini_dict2 = OrderedDict([("manjeet", "4"), ("akash", "4")]) # adding in beginning of dict both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items())) # print result print("Resultant Dictionary :" + str(both)) Input: original_dict = {'a':1, 'b':2} [END]
Python | Check order of character in string using OrderedDict( )
https://www.geeksforgeeks.org/using-ordereddict-python-check-order-characters-string/
# Function to check if string follows order of # characters defined by a pattern from collections import OrderedDict def checkOrder(input, pattern): # create empty OrderedDict # output will be like {'a': None,'b': None, 'c': None} dict = OrderedDict.fromkeys(input) # traverse generated OrderedDict parallel with # pattern string to check if order of characters # are same or not ptrlen = 0 for key, value in dict.items(): if key == pattern[ptrlen]: ptrlen = ptrlen + 1 # check if we have traverse complete # pattern string if ptrlen == (len(pattern)): return "true" # if we come out from for loop that means # order was mismatched return "false" # Driver program if __name__ == "__main__": input = "engineers rock" pattern = "er" print(checkOrder(input, pattern))
Input: string = "engineers rock"
Python | Check order of character in string using OrderedDict( ) # Function to check if string follows order of # characters defined by a pattern from collections import OrderedDict def checkOrder(input, pattern): # create empty OrderedDict # output will be like {'a': None,'b': None, 'c': None} dict = OrderedDict.fromkeys(input) # traverse generated OrderedDict parallel with # pattern string to check if order of characters # are same or not ptrlen = 0 for key, value in dict.items(): if key == pattern[ptrlen]: ptrlen = ptrlen + 1 # check if we have traverse complete # pattern string if ptrlen == (len(pattern)): return "true" # if we come out from for loop that means # order was mismatched return "false" # Driver program if __name__ == "__main__": input = "engineers rock" pattern = "er" print(checkOrder(input, pattern)) Input: string = "engineers rock" [END]
Python | Check order of character in string using OrderedDict( )
https://www.geeksforgeeks.org/using-ordereddict-python-check-order-characters-string/
def check_order(string, pattern): i, j = 0, 0 for char in string: if char == pattern[j]: j += 1 if j == len(pattern): return True i += 1 return False string = "engineers rock" pattern = "er" print(check_order(string, pattern))
Input: string = "engineers rock"
Python | Check order of character in string using OrderedDict( ) def check_order(string, pattern): i, j = 0, 0 for char in string: if char == pattern[j]: j += 1 if j == len(pattern): return True i += 1 return False string = "engineers rock" pattern = "er" print(check_order(string, pattern)) Input: string = "engineers rock" [END]
Python | Find common elements in three sorted arrays by dictionary intersection
https://www.geeksforgeeks.org/python-dictionary-intersection-find-common-elements-three-sorted-arrays/
# Function to find common elements in three # sorted arrays from collections import Counter def commonElement(ar1, ar2, ar3): # first convert lists into dictionary ar1 = Counter(ar1) ar2 = Counter(ar2) ar3 = Counter(ar3) # perform intersection operation resultDict = dict(ar1.items() & ar2.items() & ar3.items()) common = [] # iterate through resultant dictionary # and collect common elements for key, val in resultDict.items(): for i in range(0, val): common.append(key) print(common) # Driver program if __name__ == "__main__": ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] commonElement(ar1, ar2, ar3)
Input: ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100]
Python | Find common elements in three sorted arrays by dictionary intersection # Function to find common elements in three # sorted arrays from collections import Counter def commonElement(ar1, ar2, ar3): # first convert lists into dictionary ar1 = Counter(ar1) ar2 = Counter(ar2) ar3 = Counter(ar3) # perform intersection operation resultDict = dict(ar1.items() & ar2.items() & ar3.items()) common = [] # iterate through resultant dictionary # and collect common elements for key, val in resultDict.items(): for i in range(0, val): common.append(key) print(common) # Driver program if __name__ == "__main__": ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] commonElement(ar1, ar2, ar3) Input: ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] [END]
Python | Find common elements in three sorted arrays by dictionary intersection
https://www.geeksforgeeks.org/python-dictionary-intersection-find-common-elements-three-sorted-arrays/
def common_elements(ar1, ar2, ar3): n1, n2, n3 = len(ar1), len(ar2), len(ar3) i, j, k = 0, 0, 0 common = [] while i < n1 and j < n2 and k < n3: if ar1[i] == ar2[j] == ar3[k]: common.append(ar1[i]) i += 1 j += 1 k += 1 elif ar1[i] < ar2[j]: i += 1 elif ar2[j] < ar3[k]: j += 1 else: k += 1 return common ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] print(common_elements(ar1, ar2, ar3)) # Output: [20, 80] ar1 = [1, 5, 5] ar2 = [3, 4, 5, 5, 10] ar3 = [5, 5, 10, 20] print(common_elements(ar1, ar2, ar3)) # Output: [5, 5]
Input: ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100]
Python | Find common elements in three sorted arrays by dictionary intersection def common_elements(ar1, ar2, ar3): n1, n2, n3 = len(ar1), len(ar2), len(ar3) i, j, k = 0, 0, 0 common = [] while i < n1 and j < n2 and k < n3: if ar1[i] == ar2[j] == ar3[k]: common.append(ar1[i]) i += 1 j += 1 k += 1 elif ar1[i] < ar2[j]: i += 1 elif ar2[j] < ar3[k]: j += 1 else: k += 1 return common ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] ar3 = [3, 4, 15, 20, 30, 70, 80, 120] print(common_elements(ar1, ar2, ar3)) # Output: [20, 80] ar1 = [1, 5, 5] ar2 = [3, 4, 5, 5, 10] ar3 = [5, 5, 10, 20] print(common_elements(ar1, ar2, ar3)) # Output: [5, 5] Input: ar1 = [1, 5, 10, 20, 40, 80] ar2 = [6, 7, 20, 80, 100] [END]
Dictionary and counter in Python to find winner of elementsection
https://www.geeksforgeeks.org/dictionary-counter-python-find-winner-election/
# Function to find winner of an election where votes # are represented as candidate names from collections import Counter def winner(input): # convert list of candidates into dictionary # output will be likes candidates = {'A':2, 'B':4} votes = Counter(input) # create another dictionary and it's key will # be count of votes values will be name of # candidates dict = {} for value in votes.values(): # initialize empty list to each key to # insert candidate names having same # number of votes dict[value] = [] for key, value in votes.items(): dict[value].append(key) # sort keys in descending order to get maximum # value of votes maxVote = sorted(dict.keys(), reverse=True)[0] # check if more than 1 candidates have same # number of votes. If yes, then sort the list # first and print first element if len(dict[maxVote]) > 1: print(sorted(dict[maxVote])[0]) else: print(dict[maxVote][0]) # Driver program if __name__ == "__main__": input = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john", ] winner(input)
#Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie",
Dictionary and counter in Python to find winner of elementsection # Function to find winner of an election where votes # are represented as candidate names from collections import Counter def winner(input): # convert list of candidates into dictionary # output will be likes candidates = {'A':2, 'B':4} votes = Counter(input) # create another dictionary and it's key will # be count of votes values will be name of # candidates dict = {} for value in votes.values(): # initialize empty list to each key to # insert candidate names having same # number of votes dict[value] = [] for key, value in votes.items(): dict[value].append(key) # sort keys in descending order to get maximum # value of votes maxVote = sorted(dict.keys(), reverse=True)[0] # check if more than 1 candidates have same # number of votes. If yes, then sort the list # first and print first element if len(dict[maxVote]) > 1: print(sorted(dict[maxVote])[0]) else: print(dict[maxVote][0]) # Driver program if __name__ == "__main__": input = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john", ] winner(input) #Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", [END]
Dictionary and counter in Python to find winner of elementsection
https://www.geeksforgeeks.org/dictionary-counter-python-find-winner-election/
from collections import Counter votes = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john", ] # Count the votes for persons and stores in the dictionary vote_count = Counter(votes) # Find the maximum number of votes max_votes = max(vote_count.values()) # Search for people having maximum votes and store in a list lst = [i for i in vote_count.keys() if vote_count[i] == max_votes] # Sort the list and print lexicographical smallest name print(sorted(lst)[0])
#Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie",
Dictionary and counter in Python to find winner of elementsection from collections import Counter votes = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john", ] # Count the votes for persons and stores in the dictionary vote_count = Counter(votes) # Find the maximum number of votes max_votes = max(vote_count.values()) # Search for people having maximum votes and store in a list lst = [i for i in vote_count.keys() if vote_count[i] == max_votes] # Sort the list and print lexicographical smallest name print(sorted(lst)[0]) #Input : votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", [END]
Python - Key with maximum unique values
https://www.geeksforgeeks.org/python-key-with-maximum-unique-values/
# Python3 code to demonstrate working of # Key with maximum unique values # Using loop # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) max_val = 0 max_key = None for sub in test_dict: # Testing for length using len() method and # converted to set for duplicates removal if len(set(test_dict[sub])) > max_val: max_val = len(set(test_dict[sub])) max_key = sub # Printing result print("Key with maximum unique values : " + str(max_key))
#Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"??
Python - Key with maximum unique values # Python3 code to demonstrate working of # Key with maximum unique values # Using loop # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) max_val = 0 max_key = None for sub in test_dict: # Testing for length using len() method and # converted to set for duplicates removal if len(set(test_dict[sub])) > max_val: max_val = len(set(test_dict[sub])) max_key = sub # Printing result print("Key with maximum unique values : " + str(max_key)) #Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"?? [END]
Python - Key with maximum unique values
https://www.geeksforgeeks.org/python-key-with-maximum-unique-values/
# Python3 code to demonstrate working of # Key with maximum unique values # Using sorted() + lambda() + set() + values() + len() # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # one-liner to solve a problem # sorted used to reverse sort dictionary max_key = sorted(test_dict, key=lambda ele: len(set(test_dict[ele])), reverse=True)[0] # printing result print("Key with maximum unique values : " + str(max_key))
#Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"??
Python - Key with maximum unique values # Python3 code to demonstrate working of # Key with maximum unique values # Using sorted() + lambda() + set() + values() + len() # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # one-liner to solve a problem # sorted used to reverse sort dictionary max_key = sorted(test_dict, key=lambda ele: len(set(test_dict[ele])), reverse=True)[0] # printing result print("Key with maximum unique values : " + str(max_key)) #Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"?? [END]
Python - Key with maximum unique values
https://www.geeksforgeeks.org/python-key-with-maximum-unique-values/
# Python3 code to demonstrate working of # Key with maximum unique values from collections import Counter # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) max_val = 0 max_key = None for sub in test_dict: # test for length using len() # converted to Counter() to calculcate the unique values # (for duplicates removal) if len(Counter(test_dict[sub])) > max_val: max_val = len(set(test_dict[sub])) max_key = sub # printing result print("Key with maximum unique values : " + str(max_key))
#Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"??
Python - Key with maximum unique values # Python3 code to demonstrate working of # Key with maximum unique values from collections import Counter # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) max_val = 0 max_key = None for sub in test_dict: # test for length using len() # converted to Counter() to calculcate the unique values # (for duplicates removal) if len(Counter(test_dict[sub])) > max_val: max_val = len(set(test_dict[sub])) max_key = sub # printing result print("Key with maximum unique values : " + str(max_key)) #Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"?? [END]
Python - Key with maximum unique values
https://www.geeksforgeeks.org/python-key-with-maximum-unique-values/
# initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # Printing the original dictionary print("The original dictionary is : " + str(test_dict)) # Using a list comprehension to # create a list of tuples # where each tuple contains the key and # the number of unique values unique_counts = [(key, len(set(values))) for key, values in test_dict.items()] # using the max() function with a key argument to # find the key with the maximum unique values max_key = max(unique_counts, key=lambda x: x[1])[0] # Printing the result print("Key with maximum unique values : " + str(max_key)) # This code is contributed by Rayudu
#Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"??
Python - Key with maximum unique values # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # Printing the original dictionary print("The original dictionary is : " + str(test_dict)) # Using a list comprehension to # create a list of tuples # where each tuple contains the key and # the number of unique values unique_counts = [(key, len(set(values))) for key, values in test_dict.items()] # using the max() function with a key argument to # find the key with the maximum unique values max_key = max(unique_counts, key=lambda x: x[1])[0] # Printing the result print("Key with maximum unique values : " + str(max_key)) # This code is contributed by Rayudu #Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"?? [END]
Python - Key with maximum unique values
https://www.geeksforgeeks.org/python-key-with-maximum-unique-values/
from collections import defaultdict # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # create defaultdict with default value set to an empty set unique_vals = defaultdict(set) # loop through values and add elements to sets in defaultdict for key, value in test_dict.items(): # Iterating element in value for elem in value: unique_vals[key].add(elem) # Finding key with maximum length of unique values max_key = max(unique_vals, key=lambda x: len(unique_vals[x])) # Printing the result print("Key with maximum unique values : " + str(max_key))
#Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"??
Python - Key with maximum unique values from collections import defaultdict # initializing dictionary test_dict = {"Gfg": [5, 7, 5, 4, 5], "is": [6, 7, 4, 3, 3], "Best": [9, 9, 6, 5, 5]} # create defaultdict with default value set to an empty set unique_vals = defaultdict(set) # loop through values and add elements to sets in defaultdict for key, value in test_dict.items(): # Iterating element in value for elem in value: unique_vals[key].add(elem) # Finding key with maximum length of unique values max_key = max(unique_vals, key=lambda x: len(unique_vals[x])) # Printing the result print("Key with maximum unique values : " + str(max_key)) #Input : test_dict = {"Gfg" : [5, 7, 9, 4, 0], "is" : [6, 7, 4, 3, 3], "Best" : [9, 9, 6, 5, 5]}?????? Outpu"Gfg"?? [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
def duplicate_characters(string): # Create an empty dictionary chars = {} # Iterate through each character in the string for char in string: # If the character is not in the dictionary, add it if char not in chars: chars[char] = 1 else: # If the character is already in the dictionary, increment the count chars[char] += 1 # Create a list to store the duplicate characters duplicates = [] # Iterate through the dictionary to find characters with count greater than 1 for char, count in chars.items(): if count > 1: duplicates.append(char) return duplicates # Test cases print(duplicate_characters("geeksforgeeks"))
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string def duplicate_characters(string): # Create an empty dictionary chars = {} # Iterate through each character in the string for char in string: # If the character is not in the dictionary, add it if char not in chars: chars[char] = 1 else: # If the character is already in the dictionary, increment the count chars[char] += 1 # Create a list to store the duplicate characters duplicates = [] # Iterate through the dictionary to find characters with count greater than 1 for char, count in chars.items(): if count > 1: duplicates.append(char) return duplicates # Test cases print(duplicate_characters("geeksforgeeks")) #Output : ['g', 'e', 'k', 's'] [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
from collections import Counter def find_dup_char(input): # now create dictionary using counter method # which will have strings as key and their # frequencies as value WC = Counter(input) # Finding no. of occurrence of a character # and get the index of it. for letter, count in WC.items(): if count > 1: print(letter) # Driver program if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string from collections import Counter def find_dup_char(input): # now create dictionary using counter method # which will have strings as key and their # frequencies as value WC = Counter(input) # Finding no. of occurrence of a character # and get the index of it. for letter, count in WC.items(): if count > 1: print(letter) # Driver program if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input) #Output : ['g', 'e', 'k', 's'] [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
def find_dup_char(input): x = [] for i in input: if i not in x and input.count(i) > 1: x.append(i) print(" ".join(x)) # Driver program if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string def find_dup_char(input): x = [] for i in input: if i not in x and input.count(i) > 1: x.append(i) print(" ".join(x)) # Driver program if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input) #Output : ['g', 'e', 'k', 's'] [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
def find_dup_char(input): x = filter(lambda x: input.count(x) >= 2, input) print(" ".join(set(x))) # Driver Code if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string def find_dup_char(input): x = filter(lambda x: input.count(x) >= 2, input) print(" ".join(set(x))) # Driver Code if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input) #Output : ['g', 'e', 'k', 's'] [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
def find_duplicate_chars(string): # Create empty sets to store unique and duplicate characters unique_chars = set() duplicate_chars = set() # Iterate through each character in the string for char in string: # If the character is already in unique_chars, it is a duplicate if char in unique_chars: duplicate_chars.add(char) # Otherwise, add it to unique_chars else: unique_chars.add(char) return duplicate_chars # Example usage: print(find_duplicate_chars("geeksforgeeks")) # Output: ['e', 'g', 'k', 's']
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string def find_duplicate_chars(string): # Create empty sets to store unique and duplicate characters unique_chars = set() duplicate_chars = set() # Iterate through each character in the string for char in string: # If the character is already in unique_chars, it is a duplicate if char in unique_chars: duplicate_chars.add(char) # Otherwise, add it to unique_chars else: unique_chars.add(char) return duplicate_chars # Example usage: print(find_duplicate_chars("geeksforgeeks")) # Output: ['e', 'g', 'k', 's'] #Output : ['g', 'e', 'k', 's'] [END]
Find all duplicate characters in string
https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/
from functools import reduce def find_dup_char(input): x = reduce( lambda x, b: x + b if input.rindex(b) != input.index(b) and b not in x else x, input, "", ) print(x) # Driver Code if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input)
#Output : ['g', 'e', 'k', 's']
Find all duplicate characters in string from functools import reduce def find_dup_char(input): x = reduce( lambda x, b: x + b if input.rindex(b) != input.index(b) and b not in x else x, input, "", ) print(x) # Driver Code if __name__ == "__main__": input = "geeksforgeeks" find_dup_char(input) #Output : ['g', 'e', 'k', 's'] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
# Python3 code to demonstrate working of # Group Similar items to Dictionary Values List # Using defaultdict + loop from collections import defaultdict # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using defaultdict for default list res = defaultdict(list) for ele in test_list: # appending Similar values res[ele].append(ele) # printing result print("Similar grouped dictionary : " + str(dict(res)))
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list # Python3 code to demonstrate working of # Group Similar items to Dictionary Values List # Using defaultdict + loop from collections import defaultdict # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using defaultdict for default list res = defaultdict(list) for ele in test_list: # appending Similar values res[ele].append(ele) # printing result print("Similar grouped dictionary : " + str(dict(res))) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
# Python3 code to demonstrate working of # Group Similar items to Dictionary Values List # Using dictionary comprehension + Counter() from collections import Counter # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using * operator to perform multiplication res = {key: [key] * val for key, val in Counter(test_list).items()} # printing result print("Similar grouped dictionary : " + str(res))
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list # Python3 code to demonstrate working of # Group Similar items to Dictionary Values List # Using dictionary comprehension + Counter() from collections import Counter # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using * operator to perform multiplication res = {key: [key] * val for key, val in Counter(test_list).items()} # printing result print("Similar grouped dictionary : " + str(res)) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
# initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using set() to get unique elements in list unique_items = set(test_list) # creating dictionary with empty lists as values res = {key: [] for key in unique_items} # using list comprehension to group similar items [res[item].append(item) for item in test_list] # printing result print("Similar grouped dictionary : " + str(res))
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # printing original list print("The original list : " + str(test_list)) # using set() to get unique elements in list unique_items = set(test_list) # creating dictionary with empty lists as values res = {key: [] for key in unique_items} # using list comprehension to group similar items [res[item].append(item) for item in test_list] # printing result print("Similar grouped dictionary : " + str(res)) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
# Step 1 import itertools # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # Step 2 test_list.sort() # Step 3 groups = itertools.groupby(test_list) # Step 4 res = {k: list(v) for k, v in groups} # Step 5 print("Similar grouped dictionary : " + str(res))
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list # Step 1 import itertools # initializing list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] # Step 2 test_list.sort() # Step 3 groups = itertools.groupby(test_list) # Step 4 res = {k: list(v) for k, v in groups} # Step 5 print("Similar grouped dictionary : " + str(res)) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
import itertools test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] test_list.sort() grouped_lists = [list(g) for k, g in itertools.groupby(test_list)] res_dict = {lst[0]: lst for lst in grouped_lists} print("Similar grouped dictionary: ", res_dict)
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list import itertools test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] test_list.sort() grouped_lists = [list(g) for k, g in itertools.groupby(test_list)] res_dict = {lst[0]: lst for lst in grouped_lists} print("Similar grouped dictionary: ", res_dict) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
Python - Group Similar items to Dictionary Value list
https://www.geeksforgeeks.org/python-group-similar-items-to-dictionary-values-list/
test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] test_list.sort() res = {} temp = [] prev = None while test_list: curr = test_list.pop(0) if curr == prev or prev is None: temp.append(curr) else: res[prev] = temp temp = [curr] prev = curr res[prev] = temp print("Similar grouped dictionary : " + str(res))
#Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8]
Python - Group Similar items to Dictionary Value list test_list = [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] test_list.sort() res = {} temp = [] prev = None while test_list: curr = test_list.pop(0) if curr == prev or prev is None: temp.append(curr) else: res[prev] = temp temp = [curr] prev = curr res[prev] = temp print("Similar grouped dictionary : " + str(res)) #Output : The original list : [4, 6, 6, 4, 2, 2, 4, 4, 8, 5, 8] [END]
K - th Non-repeating Character in Python using List Comprehension and Ordereddict
https://www.geeksforgeeks.org/kth-non-repeating-character-python-using-list-comprehension-ordereddict/
# Function to find k'th non repeating character # in string from collections import OrderedDict def kthRepeating(input, k): # OrderedDict returns a dictionary data # structure having characters of input # string as keys in the same order they # were inserted and 0 as their default value dict = OrderedDict.fromkeys(input, 0) # now traverse input string to calculate # frequency of each character for ch in input: dict[ch] += 1 # now extract list of all keys whose value # is 1 from dict Ordered Dictionary nonRepeatDict = [key for (key, value) in dict.items() if value == 1] # now return (k-1)th character from above list if len(nonRepeatDict) < k: return "Less than k non-repeating characters in input." else: return nonRepeatDict[k - 1] # Driver function if __name__ == "__main__": input = "geeksforgeeks" k = 3 print(kthRepeating(input, k))
#Input : str = geeksforgeeks, k = 3 #Output : r
K - th Non-repeating Character in Python using List Comprehension and Ordereddict # Function to find k'th non repeating character # in string from collections import OrderedDict def kthRepeating(input, k): # OrderedDict returns a dictionary data # structure having characters of input # string as keys in the same order they # were inserted and 0 as their default value dict = OrderedDict.fromkeys(input, 0) # now traverse input string to calculate # frequency of each character for ch in input: dict[ch] += 1 # now extract list of all keys whose value # is 1 from dict Ordered Dictionary nonRepeatDict = [key for (key, value) in dict.items() if value == 1] # now return (k-1)th character from above list if len(nonRepeatDict) < k: return "Less than k non-repeating characters in input." else: return nonRepeatDict[k - 1] # Driver function if __name__ == "__main__": input = "geeksforgeeks" k = 3 print(kthRepeating(input, k)) #Input : str = geeksforgeeks, k = 3 #Output : r [END]
Python - Replace String List by Kth Dictionary value
https://www.geeksforgeeks.org/python-replace-string-by-kth-dictionary-value/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using list comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using list comprehension to solve # problem using one liner res = [ele if ele not in subs_dict else subs_dict[ele][K] for ele in test_list] # printing result print("The list after substitution : " + str(res))
#Output : The original list : ['Gfg', 'is', 'Best']
Python - Replace String List by Kth Dictionary value # Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using list comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using list comprehension to solve # problem using one liner res = [ele if ele not in subs_dict else subs_dict[ele][K] for ele in test_list] # printing result print("The list after substitution : " + str(res)) #Output : The original list : ['Gfg', 'is', 'Best'] [END]
Python - Replace String List by Kth Dictionary value
https://www.geeksforgeeks.org/python-replace-string-by-kth-dictionary-value/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using get() + list comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using list comprehension to solve problem using one liner # get() to perform presence checks and assign default value res = [subs_dict.get(ele, ele) for ele in test_list] res = [ele[K] if isinstance(ele, list) else ele for ele in res] # printing result print("The list after substitution : " + str(res))
#Output : The original list : ['Gfg', 'is', 'Best']
Python - Replace String List by Kth Dictionary value # Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using get() + list comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using list comprehension to solve problem using one liner # get() to perform presence checks and assign default value res = [subs_dict.get(ele, ele) for ele in test_list] res = [ele[K] if isinstance(ele, list) else ele for ele in res] # printing result print("The list after substitution : " + str(res)) #Output : The original list : ['Gfg', 'is', 'Best'] [END]
Python - Replace String List by Kth Dictionary value
https://www.geeksforgeeks.org/python-replace-string-by-kth-dictionary-value/?ref=leftbar-rightbar
# initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using for loop to solve problem for i in range(len(test_list)): if test_list[i] in subs_dict: test_list[i] = subs_dict[test_list[i]][K] # printing result print("The list after substitution : " + str(test_list))
#Output : The original list : ['Gfg', 'is', 'Best']
Python - Replace String List by Kth Dictionary value # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using for loop to solve problem for i in range(len(test_list)): if test_list[i] in subs_dict: test_list[i] = subs_dict[test_list[i]][K] # printing result print("The list after substitution : " + str(test_list)) #Output : The original list : ['Gfg', 'is', 'Best'] [END]
Python - Replace String List by Kth Dictionary value
https://www.geeksforgeeks.org/python-replace-string-by-kth-dictionary-value/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using map() function # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # define function to replace string def replace_string(s): return subs_dict[s][K] if s in subs_dict else s # using map() function to solve problem res = list(map(replace_string, test_list)) # printing result print("The list after substitution : " + str(res))
#Output : The original list : ['Gfg', 'is', 'Best']
Python - Replace String List by Kth Dictionary value # Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using map() function # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # define function to replace string def replace_string(s): return subs_dict[s][K] if s in subs_dict else s # using map() function to solve problem res = list(map(replace_string, test_list)) # printing result print("The list after substitution : " + str(res)) #Output : The original list : ['Gfg', 'is', 'Best'] [END]
Python - Replace String List by Kth Dictionary value
https://www.geeksforgeeks.org/python-replace-string-by-kth-dictionary-value/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using dictionary comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using dictionary comprehension to solve problem res = [subs_dict[x][K] if x in subs_dict else x for x in test_list] # printing result print("The list after substitution : " + str(res)) # Time complexity: O(n), where n is the length of the input list # Auxiliary space: O(n), since we are creating a new list of the same length as the input list.
#Output : The original list : ['Gfg', 'is', 'Best']
Python - Replace String List by Kth Dictionary value # Python3 code to demonstrate working of # Replace String by Kth Dictionary value # Using dictionary comprehension # initializing list test_list = ["Gfg", "is", "Best"] # printing original list print("The original list : " + str(test_list)) # initializing subs. Dictionary subs_dict = { "Gfg": [5, 6, 7], "is": [7, 4, 2], } # initializing K K = 2 # using dictionary comprehension to solve problem res = [subs_dict[x][K] if x in subs_dict else x for x in test_list] # printing result print("The list after substitution : " + str(res)) # Time complexity: O(n), where n is the length of the input list # Auxiliary space: O(n), since we are creating a new list of the same length as the input list. #Output : The original list : ['Gfg', 'is', 'Best'] [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : ", test_dict) # Using del to remove a dict # removes Mani del test_dict["Mani"] # Printing dictionary after removal print("The dictionary after remove is : ", test_dict) # Using del to remove a dict # raises exception del test_dict["Mani"]
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : ", test_dict) # Using del to remove a dict # removes Mani del test_dict["Mani"] # Printing dictionary after removal print("The dictionary after remove is : ", test_dict) # Using del to remove a dict # raises exception del test_dict["Mani"] #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : " + str(test_dict)) # Using pop() to remove a dict. pair # removes Mani removed_value = test_dict.pop("Mani") # Printing dictionary after removal print("The dictionary after remove is : " + str(test_dict)) print("The removed key's value is : " + str(removed_value)) print("\r") # Using pop() to remove a dict. pair # doesn't raise exception # assigns 'No Key found' to removed_value removed_value = test_dict.pop("Manjeet", "No Key found") # Printing dictionary after removal print("The dictionary after remove is : " + str(test_dict)) print("The removed key's value is : " + str(removed_value))
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : " + str(test_dict)) # Using pop() to remove a dict. pair # removes Mani removed_value = test_dict.pop("Mani") # Printing dictionary after removal print("The dictionary after remove is : " + str(test_dict)) print("The removed key's value is : " + str(removed_value)) print("\r") # Using pop() to remove a dict. pair # doesn't raise exception # assigns 'No Key found' to removed_value removed_value = test_dict.pop("Manjeet", "No Key found") # Printing dictionary after removal print("The dictionary after remove is : " + str(test_dict)) print("The removed key's value is : " + str(removed_value)) #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print( "The dictionary before performing\ remove is : " + str(test_dict) ) # Using items() + dict comprehension to remove a dict. pair # removes Mani new_dict = {key: val for key, val in test_dict.items() if key != "Mani"} # Printing dictionary after removal print("The dictionary after remove is : " + str(new_dict))
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print( "The dictionary before performing\ remove is : " + str(test_dict) ) # Using items() + dict comprehension to remove a dict. pair # removes Mani new_dict = {key: val for key, val in test_dict.items() if key != "Mani"} # Printing dictionary after removal print("The dictionary after remove is : " + str(new_dict)) #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : \n" + str(test_dict)) a_dict = {key: test_dict[key] for key in test_dict if key != "Mani"} print("The dictionary after performing remove is : \n", a_dict)
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} # Printing dictionary before removal print("The dictionary before performing remove is : \n" + str(test_dict)) a_dict = {key: test_dict[key] for key in test_dict if key != "Mani"} print("The dictionary after performing remove is : \n", a_dict) #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d y = {} # eliminate the unrequired element for key, value in test_dict.items(): if key != "Arushi": y[key] = value print(y)
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d y = {} # eliminate the unrequired element for key, value in test_dict.items(): if key != "Arushi": y[key] = value print(y) #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d del test_dict try: print(test_dict) except: print("Deleted!")
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d del test_dict try: print(test_dict) except: print("Deleted!") #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python | Ways to remove a key from dictionary
https://www.geeksforgeeks.org/python-ways-to-remove-a-key-from-dictionary/
# Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d test_dict.clear() print("Length", len(test_dict)) print(test_dict)
#Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
Python | Ways to remove a key from dictionary # Initializing dictionary test_dict = {"Arushi": 22, "Anuradha": 21, "Mani": 21, "Haritha": 21} print(test_dict) # empty the dictionary d test_dict.clear() print("Length", len(test_dict)) print(test_dict) #Output : Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} [END]
Python - Replace words from Dictionary
https://www.geeksforgeeks.org/python-replace-words-from-dictionary/
# Python3 code to demonstrate working of # Replace words from Dictionary # Using split() + join() + get() # initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # performing split() temp = test_str.split() res = [] for wrd in temp: # searching from lookp_dict res.append(lookp_dict.get(wrd, wrd)) res = " ".join(res) # printing result print("Replaced Strings : " + str(res))
#Output : The original string is : geekforgeeks best for geeks
Python - Replace words from Dictionary # Python3 code to demonstrate working of # Replace words from Dictionary # Using split() + join() + get() # initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # performing split() temp = test_str.split() res = [] for wrd in temp: # searching from lookp_dict res.append(lookp_dict.get(wrd, wrd)) res = " ".join(res) # printing result print("Replaced Strings : " + str(res)) #Output : The original string is : geekforgeeks best for geeks [END]
Python - Replace words from Dictionary
https://www.geeksforgeeks.org/python-replace-words-from-dictionary/
# Python3 code to demonstrate working of # Replace words from Dictionary # Using list comprehension + join() # initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # one-liner to solve problem res = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split()) # printing result print("Replaced Strings : " + str(res))
#Output : The original string is : geekforgeeks best for geeks
Python - Replace words from Dictionary # Python3 code to demonstrate working of # Replace words from Dictionary # Using list comprehension + join() # initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # one-liner to solve problem res = " ".join(lookp_dict.get(ele, ele) for ele in test_str.split()) # printing result print("Replaced Strings : " + str(res)) #Output : The original string is : geekforgeeks best for geeks [END]
Python - Replace words from Dictionary
https://www.geeksforgeeks.org/python-replace-words-from-dictionary/
# initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # create a temporary list to hold the replaced strings temp = [] for word in test_str.split(): temp.append(lookp_dict.get(word, word)) # join the temporary list to create the final output string res = " ".join(temp) # printing result print("Replaced Strings : " + str(res))
#Output : The original string is : geekforgeeks best for geeks
Python - Replace words from Dictionary # initializing string test_str = "geekforgeeks best for geeks" # printing original string print("The original string is : " + str(test_str)) # lookup Dictionary lookp_dict = {"best": "good and better", "geeks": "all CS aspirants"} # create a temporary list to hold the replaced strings temp = [] for word in test_str.split(): temp.append(lookp_dict.get(word, word)) # join the temporary list to create the final output string res = " ".join(temp) # printing result print("Replaced Strings : " + str(res)) #Output : The original string is : geekforgeeks best for geeks [END]
Python - Remove Dictionary Key words
https://www.geeksforgeeks.org/python-remove-dictionary-key-words/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using split() + loop + replace() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using split() + loop + replace() for key in test_dict: if key in test_str.split(" "): test_str = test_str.replace(key, "") # printing result print("The string after replace : " + str(test_str))
#Output : The original string is : gfg is best for geeks
Python - Remove Dictionary Key words # Python3 code to demonstrate working of # Remove Dictionary Key Words # Using split() + loop + replace() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using split() + loop + replace() for key in test_dict: if key in test_str.split(" "): test_str = test_str.replace(key, "") # printing result print("The string after replace : " + str(test_str)) #Output : The original string is : gfg is best for geeks [END]
Python - Remove Dictionary Key words
https://www.geeksforgeeks.org/python-remove-dictionary-key-words/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using join() + split() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using join() + split() temp = test_str.split(" ") temp1 = [word for word in temp if word.lower() not in test_dict] res = " ".join(temp1) # printing result print("The string after replace : " + str(res))
#Output : The original string is : gfg is best for geeks
Python - Remove Dictionary Key words # Python3 code to demonstrate working of # Remove Dictionary Key Words # Using join() + split() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using join() + split() temp = test_str.split(" ") temp1 = [word for word in temp if word.lower() not in test_dict] res = " ".join(temp1) # printing result print("The string after replace : " + str(res)) #Output : The original string is : gfg is best for geeks [END]
Python - Remove Dictionary Key words
https://www.geeksforgeeks.org/python-remove-dictionary-key-words/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using join() + split() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using join() + split() temp = test_str.split(" ") temp1 = [word for word in temp if word.lower() not in test_dict] res = " ".join(temp1) # printing result print("The string after replace : " + str(res))
#Output : The original string is : gfg is best for geeks
Python - Remove Dictionary Key words # Python3 code to demonstrate working of # Remove Dictionary Key Words # Using join() + split() # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using join() + split() temp = test_str.split(" ") temp1 = [word for word in temp if word.lower() not in test_dict] res = " ".join(temp1) # printing result print("The string after replace : " + str(res)) #Output : The original string is : gfg is best for geeks [END]
Python - Remove Dictionary Key words
https://www.geeksforgeeks.org/python-remove-dictionary-key-words/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using List Comprehension and Join() Method # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using List Comprehension and Join() Method new_list = [word for word in test_str.split() if word not in test_dict.keys()] test_str = " ".join(new_list) # printing result print("The string after replace : " + str(test_str))
#Output : The original string is : gfg is best for geeks
Python - Remove Dictionary Key words # Python3 code to demonstrate working of # Remove Dictionary Key Words # Using List Comprehension and Join() Method # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using List Comprehension and Join() Method new_list = [word for word in test_str.split() if word not in test_dict.keys()] test_str = " ".join(new_list) # printing result print("The string after replace : " + str(test_str)) #Output : The original string is : gfg is best for geeks [END]
Python - Remove Dictionary Key words
https://www.geeksforgeeks.org/python-remove-dictionary-key-words/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove Dictionary Key Words # Using filter() + lambda function # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using filter() + lambda function new_list = list(filter(lambda word: word not in test_dict.keys(), test_str.split())) test_str = " ".join(new_list) # printing result print("The string after replace : " + str(test_str))
#Output : The original string is : gfg is best for geeks
Python - Remove Dictionary Key words # Python3 code to demonstrate working of # Remove Dictionary Key Words # Using filter() + lambda function # initializing string test_str = "gfg is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing Dictionary test_dict = {"geeks": 1, "best": 6} # Remove Dictionary Key Words # Using filter() + lambda function new_list = list(filter(lambda word: word not in test_dict.keys(), test_str.split())) test_str = " ".join(new_list) # printing result print("The string after replace : " + str(test_str)) #Output : The original string is : gfg is best for geeks [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
from collections import Counter def remov_duplicates(input): # split input string separated by space input = input.split(" ") # now create dictionary using counter method # which will have strings as key and their # frequencies as value UniqW = Counter(input) # joins two adjacent elements in iterable way s = " ".join(UniqW.keys()) print(s) # Driver program if __name__ == "__main__": input = "Python is great and Java is also great" remov_duplicates(input)
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence from collections import Counter def remov_duplicates(input): # split input string separated by space input = input.split(" ") # now create dictionary using counter method # which will have strings as key and their # frequencies as value UniqW = Counter(input) # joins two adjacent elements in iterable way s = " ".join(UniqW.keys()) print(s) # Driver program if __name__ == "__main__": input = "Python is great and Java is also great" remov_duplicates(input) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
# Program without using any external library s = "Python is great and Java is also great" l = s.split() k = [] for i in l: # If condition is used to store unique string # in another list 'k' if s.count(i) >= 1 and (i not in k): k.append(i) print(" ".join(k))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence # Program without using any external library s = "Python is great and Java is also great" l = s.split() k = [] for i in l: # If condition is used to store unique string # in another list 'k' if s.count(i) >= 1 and (i not in k): k.append(i) print(" ".join(k)) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
# Python3 program string = "Python is great and Java is also great" print(" ".join(dict.fromkeys(string.split())))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence # Python3 program string = "Python is great and Java is also great" print(" ".join(dict.fromkeys(string.split()))) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
string = "Python is great and Java is also great" print(" ".join(set(string.split())))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence string = "Python is great and Java is also great" print(" ".join(set(string.split()))) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
# Program using operator.countOf() import operator as op s = "Python is great and Java is also great" l = s.split() k = [] for i in l: # If condition is used to store unique string # in another list 'k' if op.countOf(l, i) >= 1 and (i not in k): k.append(i) print(" ".join(k))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence # Program using operator.countOf() import operator as op s = "Python is great and Java is also great" l = s.split() k = [] for i in l: # If condition is used to store unique string # in another list 'k' if op.countOf(l, i) >= 1 and (i not in k): k.append(i) print(" ".join(k)) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
def remove_duplicates(sentence): words = sentence.split(" ") result = [] for word in words: if word not in result: result.append(word) return " ".join(result) sentence = "Python is great and Java is also great" print(remove_duplicates(sentence))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence def remove_duplicates(sentence): words = sentence.split(" ") result = [] for word in words: if word not in result: result.append(word) return " ".join(result) sentence = "Python is great and Java is also great" print(remove_duplicates(sentence)) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
def remove_duplicates(sentence): words = sentence.split(" ") if len(words) == 1: return words[0] if words[0] in words[1:]: return remove_duplicates(" ".join(words[1:])) else: return words[0] + " " + remove_duplicates(" ".join(words[1:])) sentence = "Python is great and Java is also great" print(remove_duplicates(sentence))
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence def remove_duplicates(sentence): words = sentence.split(" ") if len(words) == 1: return words[0] if words[0] in words[1:]: return remove_duplicates(" ".join(words[1:])) else: return words[0] + " " + remove_duplicates(" ".join(words[1:])) sentence = "Python is great and Java is also great" print(remove_duplicates(sentence)) #Input : Geeks for Geeks #Output : Geeks for [END]
Python | Remove all duplicates words from a given sentence
https://www.geeksforgeeks.org/python-remove-duplicates-words-given-sentence/
from functools import reduce def remove_duplicates(input_str): words = input_str.split() unique_words = reduce( lambda x, y: x if y in x else x + [y], [ [], ] + words, ) return " ".join(unique_words) input_str = "Python is great and Java is also great" print(remove_duplicates(input_str)) # This code is contributed by Vinay Pinjala.
#Input : Geeks for Geeks #Output : Geeks for
Python | Remove all duplicates words from a given sentence from functools import reduce def remove_duplicates(input_str): words = input_str.split() unique_words = reduce( lambda x, y: x if y in x else x + [y], [ [], ] + words, ) return " ".join(unique_words) input_str = "Python is great and Java is also great" print(remove_duplicates(input_str)) # This code is contributed by Vinay Pinjala. #Input : Geeks for Geeks #Output : Geeks for [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
# Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values # Using Counter() + list comprehension from collections import Counter # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values # Using Counter() + list comprehension cnt = Counter() for idx in test_dict.values(): cnt.update(idx) res = {idx: [key for key in j if cnt[key] == 1] for idx, j in test_dict.items()} # printing result print("Uncommon elements records : " + str(res))
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values # Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values # Using Counter() + list comprehension from collections import Counter # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values # Using Counter() + list comprehension cnt = Counter() for idx in test_dict.values(): cnt.update(idx) res = {idx: [key for key in j if cnt[key] == 1] for idx, j in test_dict.items()} # printing result print("Uncommon elements records : " + str(res)) #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
# Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values x = [] for i in test_dict.keys(): x.extend(test_dict[i]) y = [] for i in x: if x.count(i) == 1: y.append(i) res = dict() for i in test_dict.keys(): a = [] for j in test_dict[i]: if j in y: a.append(j) res[i] = a # printing result print("Uncommon elements records : " + str(res))
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values # Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values x = [] for i in test_dict.keys(): x.extend(test_dict[i]) y = [] for i in x: if x.count(i) == 1: y.append(i) res = dict() for i in test_dict.keys(): a = [] for j in test_dict[i]: if j in y: a.append(j) res[i] = a # printing result print("Uncommon elements records : " + str(res)) #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
# Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values import operator as op # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values x = [] for i in test_dict.keys(): x.extend(test_dict[i]) y = [] for i in x: if op.countOf(x, i) == 1: y.append(i) res = dict() for i in test_dict.keys(): a = [] for j in test_dict[i]: if j in y: a.append(j) res[i] = a # printing result print("Uncommon elements records : " + str(res))
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values # Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values import operator as op # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values x = [] for i in test_dict.keys(): x.extend(test_dict[i]) y = [] for i in x: if op.countOf(x, i) == 1: y.append(i) res = dict() for i in test_dict.keys(): a = [] for j in test_dict[i]: if j in y: a.append(j) res[i] = a # printing result print("Uncommon elements records : " + str(res)) #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
from collections import defaultdict test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } print("The original dictionary : " + str(test_dict)) d = defaultdict(set) for lst in test_dict.values(): for item in lst: d[item].add(id(lst)) res = {} for k, lst in test_dict.items(): new_lst = [] for item in lst: if len(d[item]) == 1: new_lst.append(item) res[k] = new_lst print("Uncommon elements records : " + str(res))
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values from collections import defaultdict test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } print("The original dictionary : " + str(test_dict)) d = defaultdict(set) for lst in test_dict.values(): for item in lst: d[item].add(id(lst)) res = {} for k, lst in test_dict.items(): new_lst = [] for item in lst: if len(d[item]) == 1: new_lst.append(item) res[k] = new_lst print("Uncommon elements records : " + str(res)) #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
# Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values from collections import Counter # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values flat_list = [val for sublist in test_dict.values() for val in sublist] unique_values = [val for val, count in Counter(flat_list).items() if count == 1] res = { key: [val for val in values if val in unique_values] for key, values in test_dict.items() } # printing result print("Uncommon elements records : " + str(res))
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values # Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values from collections import Counter # initializing dictionary test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } # printing original dictionary print("The original dictionary : " + str(test_dict)) # Remove duplicate values across Dictionary Values flat_list = [val for sublist in test_dict.values() for val in sublist] unique_values = [val for val, count in Counter(flat_list).items() if count == 1] res = { key: [val for val in values if val in unique_values] for key, values in test_dict.items() } # printing result print("Uncommon elements records : " + str(res)) #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python - Remove duplicate values across Dictionary values
https://www.geeksforgeeks.org/python-remove-duplicate-values-across-dictionary-values/
import numpy as np test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } print("The original dictionary : " + str(test_dict)) d = {} for lst in test_dict.values(): unique_lst = np.unique(lst) for item in unique_lst: if item in d: d[item] += 1 else: d[item] = 1 res = {} for k, lst in test_dict.items(): new_lst = [] for item in lst: if d[item] == 1: new_lst.append(item) res[k] = new_lst print("Uncommon elements records : " + str(res)) # This code is contributed by Jyothi pinjala.
#Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]}
Python - Remove duplicate values across Dictionary values import numpy as np test_dict = { "Manjeet": [1, 4, 5, 6], "Akash": [1, 8, 9], "Nikhil": [10, 22, 4], "Akshat": [5, 11, 22], } print("The original dictionary : " + str(test_dict)) d = {} for lst in test_dict.values(): unique_lst = np.unique(lst) for item in unique_lst: if item in d: d[item] += 1 else: d[item] = 1 res = {} for k, lst in test_dict.items(): new_lst = [] for item in lst: if d[item] == 1: new_lst.append(item) res[k] = new_lst print("Uncommon elements records : " + str(res)) # This code is contributed by Jyothi pinjala. #Output : The original dictionary : {'Manjeet': [1, 4, 5, 6], 'Akash': [1, 8, 9], 'Nikhil': [10, 22, 4], 'Akshat': [5, 11, 22]} [END]
Python Dictionary to find mirror characters in a string
https://www.geeksforgeeks.org/python-dictionary-find-mirror-characters-string/
# function to mirror characters of a string def mirrorChars(input, k): # create dictionary original = "abcdefghijklmnopqrstuvwxyz" reverse = "zyxwvutsrqponmlkjihgfedcba" dictChars = dict(zip(original, reverse)) # separate out string after length k to change # characters in mirror prefix = input[0 : k - 1] suffix = input[k - 1 :] mirror = "" # change into mirror for i in range(0, len(suffix)): mirror = mirror + dictChars[suffix[i]] # concat prefix and mirrored part print(prefix + mirror) # Driver program if __name__ == "__main__": input = "paradox" k = 3 mirrorChars(input, k)
#Input : N = 3 paradox
Python Dictionary to find mirror characters in a string # function to mirror characters of a string def mirrorChars(input, k): # create dictionary original = "abcdefghijklmnopqrstuvwxyz" reverse = "zyxwvutsrqponmlkjihgfedcba" dictChars = dict(zip(original, reverse)) # separate out string after length k to change # characters in mirror prefix = input[0 : k - 1] suffix = input[k - 1 :] mirror = "" # change into mirror for i in range(0, len(suffix)): mirror = mirror + dictChars[suffix[i]] # concat prefix and mirrored part print(prefix + mirror) # Driver program if __name__ == "__main__": input = "paradox" k = 3 mirrorChars(input, k) #Input : N = 3 paradox [END]
Counting the frequencies in a list using dictionary in Python
https://www.geeksforgeeks.org/counting-the-frequencies-in-a-list-using-dictionary-in-python/
def CountFrequency(my_list): # Creating an empty dictionary freq = {} for item in my_list: if item in freq: freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)
Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting the frequencies in a list using dictionary in Python def CountFrequency(my_list): # Creating an empty dictionary freq = {} for item in my_list: if item in freq: freq[item] += 1 else: freq[item] = 1 for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list) Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] [END]
Counting the frequencies in a list using dictionary in Python
https://www.geeksforgeeks.org/counting-the-frequencies-in-a-list-using-dictionary-in-python/
import operator def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = my_list.count(items) for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)
Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting the frequencies in a list using dictionary in Python import operator def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = my_list.count(items) for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list) Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] [END]
Counting the frequencies in a list using dictionary in Python
https://www.geeksforgeeks.org/counting-the-frequencies-in-a-list-using-dictionary-in-python/
def CountFrequency(my_list): # Creating an empty dictionary count = {} for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]: count[i] = count.get(i, 0) + 1 return count # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] print(CountFrequency(my_list))
Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting the frequencies in a list using dictionary in Python def CountFrequency(my_list): # Creating an empty dictionary count = {} for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]: count[i] = count.get(i, 0) + 1 return count # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] print(CountFrequency(my_list)) Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] [END]
Counting the frequencies in a list using dictionary in Python
https://www.geeksforgeeks.org/counting-the-frequencies-in-a-list-using-dictionary-in-python/
import operator def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = operator.countOf(my_list, items) for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list)
Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
Counting the frequencies in a list using dictionary in Python import operator def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = operator.countOf(my_list, items) for key, value in freq.items(): print("% d : % d" % (key, value)) # Driver function if __name__ == "__main__": my_list = [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] CountFrequency(my_list) Input: [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2] [END]
Python - Dictionary Value mean
https://www.geeksforgeeks.org/python-dictionary-values-mean/
# Python3 code to demonstrate working of # Dictionary Values Mean # Using loop + len() # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # loop to sum all values res = 0 for val in test_dict.values(): res += val # using len() to get total keys for mean computation res = res / len(test_dict) # printing result print("The computed mean : " + str(res))
#Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Python - Dictionary Value mean # Python3 code to demonstrate working of # Dictionary Values Mean # Using loop + len() # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # loop to sum all values res = 0 for val in test_dict.values(): res += val # using len() to get total keys for mean computation res = res / len(test_dict) # printing result print("The computed mean : " + str(res)) #Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. [END]
Python - Dictionary Value mean
https://www.geeksforgeeks.org/python-dictionary-values-mean/
# Python3 code to demonstrate working of # Dictionary Values Mean # Using sum() + len() + values() # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # values extracted using values() # one-liner solution to problem. res = sum(test_dict.values()) / len(test_dict) # printing result print("The computed mean : " + str(res))
#Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Python - Dictionary Value mean # Python3 code to demonstrate working of # Dictionary Values Mean # Using sum() + len() + values() # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # values extracted using values() # one-liner solution to problem. res = sum(test_dict.values()) / len(test_dict) # printing result print("The computed mean : " + str(res)) #Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. [END]
Python - Dictionary Value mean
https://www.geeksforgeeks.org/python-dictionary-values-mean/
# Python3 code to demonstrate working of # Dictionary Values Mean import statistics # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) res = statistics.mean(list(test_dict.values())) # printing result print("The computed mean : " + str(res))
#Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Python - Dictionary Value mean # Python3 code to demonstrate working of # Dictionary Values Mean import statistics # initializing dictionary test_dict = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} # printing original dictionary print("The original dictionary is : " + str(test_dict)) res = statistics.mean(list(test_dict.values())) # printing result print("The computed mean : " + str(res)) #Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. [END]
Python - Dictionary Value mean
https://www.geeksforgeeks.org/python-dictionary-values-mean/
from functools import reduce def accumulate(x, y): return x + y def dict_mean(d): values_sum = reduce(accumulate, d.values()) mean = values_sum / len(d) return mean # Example usage d = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} print("Mean:", dict_mean(d))
#Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Python - Dictionary Value mean from functools import reduce def accumulate(x, y): return x + y def dict_mean(d): values_sum = reduce(accumulate, d.values()) mean = values_sum / len(d) return mean # Example usage d = {"Gfg": 4, "is": 7, "Best": 8, "for": 6, "Geeks": 10} print("Mean:", dict_mean(d)) #Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} #Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. [END]
Python counter and dictionary intersection example (Make a string using delementsetion and rearrangement)
https://www.geeksforgeeks.org/python-counter-dictionary-intersection-example-make-string-using-deletion-rearrangement/
# Python code to find if we can make first string # from second by deleting some characters from # second and rearranging remaining characters. from collections import Counter def makeString(str1, str2): # convert both strings into dictionaries # output will be like str1="aabbcc", # dict1={'a':2,'b':2,'c':2} # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2} dict1 = Counter(str1) dict2 = Counter(str2) # take intersection of two dictionaries # output will be result = {'a':1,'b':2,'c':2} result = dict1 & dict2 # compare resultant dictionary with first # dictionary comparison first compares keys # and then compares their corresponding values return result == dict1 # Driver program if __name__ == "__main__": str1 = "ABHISHEKsinGH" str2 = "gfhfBHkooIHnfndSHEKsiAnG" if makeString(str1, str2) == True: print("Possible") else: print("Not Possible")
#Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG
Python counter and dictionary intersection example (Make a string using delementsetion and rearrangement) # Python code to find if we can make first string # from second by deleting some characters from # second and rearranging remaining characters. from collections import Counter def makeString(str1, str2): # convert both strings into dictionaries # output will be like str1="aabbcc", # dict1={'a':2,'b':2,'c':2} # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2} dict1 = Counter(str1) dict2 = Counter(str2) # take intersection of two dictionaries # output will be result = {'a':1,'b':2,'c':2} result = dict1 & dict2 # compare resultant dictionary with first # dictionary comparison first compares keys # and then compares their corresponding values return result == dict1 # Driver program if __name__ == "__main__": str1 = "ABHISHEKsinGH" str2 = "gfhfBHkooIHnfndSHEKsiAnG" if makeString(str1, str2) == True: print("Possible") else: print("Not Possible") #Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG [END]
Python dictionary, set and counter to check if frequencies can become same
https://www.geeksforgeeks.org/python-dictionary-set-counter-check-frequencies-can-become/
# Function to Check if frequency of all characters # can become same by one removal from collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict = Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same) > 2: print("No") elif len(same) == 2 and same[1] - same[0] > 1: print("No") else: print("Yes") # now check if frequency of all characters # can become same # Driver program if __name__ == "__main__": input = "xxxyyzzt" allSame(input)
Input : str = ?????????xyyz
Python dictionary, set and counter to check if frequencies can become same # Function to Check if frequency of all characters # can become same by one removal from collections import Counter def allSame(input): # calculate frequency of each character # and convert string into dictionary dict = Counter(input) # now get list of all values and push it # in set same = list(set(dict.values())) if len(same) > 2: print("No") elif len(same) == 2 and same[1] - same[0] > 1: print("No") else: print("Yes") # now check if frequency of all characters # can become same # Driver program if __name__ == "__main__": input = "xxxyyzzt" allSame(input) Input : str = ?????????xyyz [END]
Scraping And Finding Ordered Words In A Dictionary using Python
https://www.geeksforgeeks.org/scraping-and-finding-ordered-words-in-a-dictionary-using-python/
# Python program to find ordered words import requests # Scrapes the words from the URL below and stores # them in a list def getWords(): # contains about 2500 words url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" fetchData = requests.get(url) # extracts the content of the webpage wordList = fetchData.content # decodes the UTF-8 encoded text and splits the # string to turn it into a list of words wordList = wordList.decode("utf-8").split() return wordList # function to determine whether a word is ordered or not def isOrdered(): # fetching the wordList collection = getWords() # since the first few of the elements of the # dictionary are numbers, getting rid of those # numbers by slicing off the first 17 elements collection = collection[16:] word = "" for word in collection: result = "Word is ordered" i = 0 l = len(word) - 1 if len(word) < 3: # skips the 1 and 2 lettered strings continue # traverses through all characters of the word in pairs while i < l: if ord(word[i]) > ord(word[i + 1]): result = "Word is not ordered" break else: i += 1 # only printing the ordered words if result == "Word is ordered": print(word, ": ", result) # execute isOrdered() function if __name__ == "__main__": isOrdered()
#Output : pip install requests
Scraping And Finding Ordered Words In A Dictionary using Python # Python program to find ordered words import requests # Scrapes the words from the URL below and stores # them in a list def getWords(): # contains about 2500 words url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" fetchData = requests.get(url) # extracts the content of the webpage wordList = fetchData.content # decodes the UTF-8 encoded text and splits the # string to turn it into a list of words wordList = wordList.decode("utf-8").split() return wordList # function to determine whether a word is ordered or not def isOrdered(): # fetching the wordList collection = getWords() # since the first few of the elements of the # dictionary are numbers, getting rid of those # numbers by slicing off the first 17 elements collection = collection[16:] word = "" for word in collection: result = "Word is ordered" i = 0 l = len(word) - 1 if len(word) < 3: # skips the 1 and 2 lettered strings continue # traverses through all characters of the word in pairs while i < l: if ord(word[i]) > ord(word[i + 1]): result = "Word is not ordered" break else: i += 1 # only printing the ordered words if result == "Word is ordered": print(word, ": ", result) # execute isOrdered() function if __name__ == "__main__": isOrdered() #Output : pip install requests [END]
Possible Words using given characters in Python
https://www.geeksforgeeks.org/possible-words-using-given-characters-python/
# Function to print words which can be created # using given set of characters def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): for word in lwords: flag = 1 chars = charCount(word) for key in chars: if key not in charSet: flag = 0 else: if charSet.count(key) != chars[key]: flag = 0 if flag == 1: print(word) if __name__ == "__main__": input = ["goo", "bat", "me", "eat", "goal", "boy", "run"] charSet = ["e", "o", "b", "a", "m", "g", "l"] possible_words(input, charSet)
#Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l']
Possible Words using given characters in Python # Function to print words which can be created # using given set of characters def charCount(word): dict = {} for i in word: dict[i] = dict.get(i, 0) + 1 return dict def possible_words(lwords, charSet): for word in lwords: flag = 1 chars = charCount(word) for key in chars: if key not in charSet: flag = 0 else: if charSet.count(key) != chars[key]: flag = 0 if flag == 1: print(word) if __name__ == "__main__": input = ["goo", "bat", "me", "eat", "goal", "boy", "run"] charSet = ["e", "o", "b", "a", "m", "g", "l"] possible_words(input, charSet) #Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] [END]
Possible Words using given characters in Python
https://www.geeksforgeeks.org/possible-words-using-given-characters-python/
def find_words(dictionary, characters, word=""): # base case: if the word is in the dictionary, print it if word in dictionary: print(word) # recursive case: for each character in the characters list, make a new list of characters # with that character removed, and call find_words with the new list of characters and the # current word appended with the current character for char in characters: new_characters = characters.copy() new_characters.remove(char) find_words(dictionary, new_characters, word + char) # example usage dictionary = ["go", "bat", "me", "eat", "goal", "boy", "run"] characters = ["e", "o", "b", "a", "m", "g", "l"] find_words(dictionary, characters)
#Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l']
Possible Words using given characters in Python def find_words(dictionary, characters, word=""): # base case: if the word is in the dictionary, print it if word in dictionary: print(word) # recursive case: for each character in the characters list, make a new list of characters # with that character removed, and call find_words with the new list of characters and the # current word appended with the current character for char in characters: new_characters = characters.copy() new_characters.remove(char) find_words(dictionary, new_characters, word + char) # example usage dictionary = ["go", "bat", "me", "eat", "goal", "boy", "run"] characters = ["e", "o", "b", "a", "m", "g", "l"] find_words(dictionary, characters) #Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] [END]
Possible Words using given characters in Python
https://www.geeksforgeeks.org/possible-words-using-given-characters-python/
def possible_words(Dict, arr): arr_set = set(arr) result = [] for word in Dict: if set(word).issubset(arr_set): result.append(word) return result Dict = ["go", "bat", "me", "eat", "goal", "boy", "run"] arr = ["e", "o", "b", "a", "m", "g", "l"] print(possible_words(Dict, arr))
#Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l']
Possible Words using given characters in Python def possible_words(Dict, arr): arr_set = set(arr) result = [] for word in Dict: if set(word).issubset(arr_set): result.append(word) return result Dict = ["go", "bat", "me", "eat", "goal", "boy", "run"] arr = ["e", "o", "b", "a", "m", "g", "l"] print(possible_words(Dict, arr)) #Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] [END]
Python - Maximum record value key in dictionary
https://www.geeksforgeeks.org/python-maximum-record-value-key-in-dictionary/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Maximum record value key in dictionary # Using loop # initializing dictionary test_dict = { "gfg": {"Manjeet": 5, "Himani": 10}, "is": {"Manjeet": 8, "Himani": 9}, "best": {"Manjeet": 10, "Himani": 15}, } # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing search key key = "Himani" # Maximum record value key in dictionary # Using loop res = None res_max = 0 for sub in test_dict: if test_dict[sub][key] > res_max: res_max = test_dict[sub][key] res = sub # printing result print("The required key is : " + str(res))
#Output : The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
Python - Maximum record value key in dictionary # Python3 code to demonstrate working of # Maximum record value key in dictionary # Using loop # initializing dictionary test_dict = { "gfg": {"Manjeet": 5, "Himani": 10}, "is": {"Manjeet": 8, "Himani": 9}, "best": {"Manjeet": 10, "Himani": 15}, } # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing search key key = "Himani" # Maximum record value key in dictionary # Using loop res = None res_max = 0 for sub in test_dict: if test_dict[sub][key] > res_max: res_max = test_dict[sub][key] res = sub # printing result print("The required key is : " + str(res)) #Output : The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}} [END]
Python - Maximum record value key in dictionary
https://www.geeksforgeeks.org/python-maximum-record-value-key-in-dictionary/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Maximum record value key in dictionary # Using max() + lambda function # initializing dictionary test_dict = { "gfg": {"Manjeet": 5, "Himani": 10}, "is": {"Manjeet": 8, "Himani": 9}, "best": {"Manjeet": 10, "Himani": 15}, } # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing search key key = "Himani" # Maximum record value key in dictionary # Using max() + lambda function res = max(test_dict, key=lambda sub: test_dict[sub][key]) # printing result print("The required key is : " + str(res))
#Output : The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
Python - Maximum record value key in dictionary # Python3 code to demonstrate working of # Maximum record value key in dictionary # Using max() + lambda function # initializing dictionary test_dict = { "gfg": {"Manjeet": 5, "Himani": 10}, "is": {"Manjeet": 8, "Himani": 9}, "best": {"Manjeet": 10, "Himani": 15}, } # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing search key key = "Himani" # Maximum record value key in dictionary # Using max() + lambda function res = max(test_dict, key=lambda sub: test_dict[sub][key]) # printing result print("The required key is : " + str(res)) #Output : The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}} [END]