How to use test_list_of_dicts method in assertpy

Best Python code snippet using assertpy_python

Module 4 - sync_code.py

Source:Module 4 - sync_code.py Github

copy

Full Screen

1# IMPORTS REQUIRED PACKAGES2import random3import string4import time5import pandas as pd6import matplotlib.pyplot as plt7import seaborn as sns8# DEFINES VARIOUS SORT FUNCTIONS9# Defines quicksort function10def quickSort(list_of_dicts, key): 11 # base case, arrays with 0 or 1 element are already "sorted"12 if len(list_of_dicts) < 2:13 return list_of_dicts14 else:15 # assigns pivot element16 pivot_element = list_of_dicts[0]17 # creates sub-array of all the elements less than the identified pivot18 less = [i for i in list_of_dicts[1:] if i[key] <= pivot_element[key]]19 # creates sub-array of all the elements greater than the identified pivot20 greater = [i for i in list_of_dicts[1:] if i[key] > pivot_element[key]]21 # recursive call of quicksort on the less-than and greater-than arrays (nesting the pivot in between)22 return quickSort(less,key) + [pivot_element] + quickSort(greater,key)23# Uses version of selection sort function from Week 224def selectionSort(list_of_dicts, key):25 for i in range(len(list_of_dicts)): 26 min_index = i 27 min_value = list_of_dicts[i][key]28 # cycles through remaining array to find next min value29 for j in range(i+1, len(list_of_dicts)): 30 if list_of_dicts[j][key] < min_value: 31 min_index = j 32 min_value = list_of_dicts[j][key]33 # Swap the first element and the minimum element within the remaining unsorted portion of the array34 list_of_dicts[i], list_of_dicts[min_index] = list_of_dicts[min_index], list_of_dicts[i] 35 return list_of_dicts36# Defines Bubble sort function (from geeksforgeeks.org)37def bubbleSort(list_of_dicts,key): 38 n = len(list_of_dicts) 39 # Traverse through all array elements 40 for i in range(n): 41 # Last i elements are already in place 42 for j in range(0, n-i-1): 43 # traverse the array from 0 to n-i-1 44 # Swap if the element found is greater 45 # than the next element 46 if list_of_dicts[j][key] > list_of_dicts[j+1][key] : 47 list_of_dicts[j], list_of_dicts[j+1] = list_of_dicts[j+1], list_of_dicts[j] 48 return list_of_dicts49# Defines Insertion sort function (from geeksforgeeks.org)50def insertionSort(list_of_dicts, key): 51 # Traverse through 1 to len(arr) 52 for i in range(1, len(list_of_dicts)): 53 comp_element = list_of_dicts[i]54 # Move elements of arr[0..i-1], that are 55 # greater than key, to one position ahead 56 # of their current position 57 j = i-158 while j >=0 and comp_element[key] < list_of_dicts[j][key] : 59 list_of_dicts[j+1] = list_of_dicts[j] 60 j -= 161 list_of_dicts[j+1] = comp_element 62 return list_of_dicts63# Defines Strand sort function (drafted myself from online pseudo-code)64# Defines merge of pre-sorted lists first65def my_merge(l1, l2, key):66 result = []67 while (l1 and l2):68 if (l1[0][key] <= l2[0][key]):69 result.append(l1.pop(0))70 else:71 result.append(l2.pop(0))72 # Add the remaining of the lists73 result.extend(l1 if l1 else l2)74 return result75def strandSort(list_of_dicts,key):76 if len(list_of_dicts) < 2:77 return list_of_dicts 78 result_list_of_dicts = []79 while len(list_of_dicts)>0:80 i = 081 sublist = [list_of_dicts.pop(0)]82 while i < len(list_of_dicts):83 if list_of_dicts[i][key] > sublist[-1][key]:84 sublist.append(list_of_dicts.pop(i))85 else:86 i = i + 187 result_list_of_dicts = my_merge(sublist,result_list_of_dicts,key)88 return result_list_of_dicts89# Defines Gnome sort function (from geeksforgeeks.org with slight tweaks)90def gnomeSort(list_of_dicts,key): 91 index = 192 while index < len(list_of_dicts): 93 if index == 0: 94 index = index + 195 if list_of_dicts[index][key] >= list_of_dicts[index - 1][key]: 96 index = index + 197 else: 98 list_of_dicts[index], list_of_dicts[index-1] = list_of_dicts[index-1], list_of_dicts[index] 99 index = index - 1100 return list_of_dicts 101# Functional testing of quicksort, bubblesort, gnomesort, insertionsort, selectionsort, and strandsort functions102test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}103 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}104 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]105quickSort(test_list_of_dicts,'city')106test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}107 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}108 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]109bubbleSort(test_list_of_dicts,'city')110test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}111 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}112 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]113gnomeSort(test_list_of_dicts,'city')114test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}115 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}116 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]117insertionSort(test_list_of_dicts,'city')118test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}119 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}120 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]121selectionSort(test_list_of_dicts,'city')122test_list_of_dicts = [{'first_name':'Sarah', 'last_name':'Martin', 'city':'NYC'}123 , {'first_name':'Rachel', 'last_name':'Martin', 'city':'Berlin'}124 , {'first_name':'David', 'last_name':'Martin', 'city':'Stamford'}]125strandSort(test_list_of_dicts,'city')126# GENERATES TEST DATA127# Instantiates (currently sorted) list of state abbrebiations128states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", 129 "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", 130 "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", 131 "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", 132 "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]133# Randomly shuffles states list134random.seed(2)135random.shuffle(states)136# Generates 50 randomly generated 10-character string as 'first names' and separately, 'last names'137random.seed(3)138first_names = ["".join(random.choices(string.ascii_lowercase, k=10)) for _ in range(50)]139random.seed(4)140last_names = ["".join(random.choices(string.ascii_lowercase, k=10)) for _ in range(50)]141# Checks to see there are no dupes with the names142len(first_names) == len(set(first_names))143len(last_names) == len(set(last_names))144# confirmed!145# Combines lists into dictionary and then converts to list of dictionaries146persons_dict = {'first_name':first_names, 'last_name':last_names, 'address':states}147persons_list = pd.DataFrame(persons_dict).to_dict('records')148# TESTS 1. QUICK SORT, 2. BUBBLE SORT, 3. GNOME SORT, 4. INSERTION SORT, 5. SELECTION SORT, AND 6. STRAND SORT149# due to in-place sorting or elimination of the original data,150# I'll create copies of the test data for each sort function for 2 sorts151persons_list_quick1 = persons_list.copy()152persons_list_bubble1 = persons_list.copy()153persons_list_gnome1 = persons_list.copy()154persons_list_insertion1 = persons_list.copy()155persons_list_selection1 = persons_list.copy()156persons_list_strand1 = persons_list.copy()157persons_list_quick2 = persons_list.copy()158persons_list_bubble2 = persons_list.copy()159persons_list_gnome2 = persons_list.copy()160persons_list_insertion2 = persons_list.copy()161persons_list_selection2 = persons_list.copy()162persons_list_strand2 = persons_list.copy()163# instantiates list to capture time test results164time_results = []165def time_testing(sort_method,method_label,data1,data2):166 start1 = time.perf_counter()167 by_last_name = sort_method(data1,'last_name')168 end1 = time.perf_counter()169 start2 = time.perf_counter()170 by_address = sort_method(data2,'address')171 end2 = time.perf_counter()172 first_sort_time = (end1 - start1)*1000173 second_sort_time = (end2 - start2)*1000174 time_results.append({'Method':method_label175 ,'Sort Key':'Last Name'176 ,'Sort Time':first_sort_time})177 time_results.append({'Method':method_label178 ,'Sort Key':'Address'179 ,'Sort Time':second_sort_time})180 time_results.append({'Method':method_label181 ,'Sort Key':'Average'182 ,'Sort Time':(first_sort_time + second_sort_time)/2})183 return by_last_name, by_address184time_testing(quickSort,'Quick Sort',persons_list_quick1,persons_list_quick2)185time_testing(bubbleSort,'Bubble Sort',persons_list_bubble1,persons_list_bubble2)186time_testing(gnomeSort,'Gnome Sort',persons_list_gnome1,persons_list_gnome2)187time_testing(insertionSort,'Insertion Sort',persons_list_insertion1,persons_list_insertion2)188time_testing(selectionSort,'Selection Sort',persons_list_selection1,persons_list_selection2)189time_testing(strandSort,'Strand Sort',persons_list_strand1,persons_list_strand2)190results_df = pd.DataFrame(time_results)191sns.catplot(x="Sort Key", y="Sort Time"192 , hue = "Method", data=results_df)193plt.show()194sns.catplot(x="Sort Key", y="Sort Time"195 , hue = "Method", jitter = False196 , data=results_df.loc[~results_df['Method'].isin(['Gnome Sort','Bubble Sort'])])...

Full Screen

Full Screen

simple.py

Source:simple.py Github

copy

Full Screen

1'''2Hacer una función que genere una lista de diccionarios3que contengan id y edad, donde4edad sea un número aleatorio entre 1 y 100 y la longitud de la5lista sea de 10 elementos. Retornar la lista.6Hacer otra función que reciba lo generado en la primer7función y ordenarlo de mayor a menor.8Printear el id de la persona más joven y más vieja.9Devolver la lista ordenada.10'''11import random12from operator import itemgetter13def list_of_dicts():14 '''15 Genera una lista de diccionarios de 10 elementos.16 Las keys son "ID" y "Edad" donde edad es un número17 aleatorio entre 1 y 100.18 :return: list19 >>> test_list_of_dicts = list_of_dicts()20 >>> len(test_list_of_dicts) == 1021 True22 >>> 1 <= test_list_of_dicts[0]["Edad"] <= 10023 True24 '''25 LONG_LIST = 1026 list_dicts = []27 for element in range(1, LONG_LIST + 1):28 context_dict = {29 'ID': element,30 'Edad': random.randint(1, 101),31 }32 list_dicts.append(context_dict)33 return list_dicts34def sort_list(list_dicts):35 '''36 Recibe una lista y la ordena de mayor a menor.37 Printea el "ID" de la persona de mayor edad y la de menor edad.38 Devuelve la lista ordenada.39 :param list_dicts: list40 :return: list41 >>> ejemplo_lista = [{'ID': 1, 'Edad': 51}, {'ID': 2, 'Edad': 54}, {'ID': 3, 'Edad': 31}, {'ID': 4, 'Edad': 74}, {'ID': 5, 'Edad': 21}, {'ID': 6, 'Edad': 19}, {'ID': 7, 'Edad': 77}, {'ID': 8, 'Edad': 62}, {'ID': 9, 'Edad': 85}, {'ID': 10, 'Edad': 29}]42 >>> sort_list(ejemplo_lista)43 ID y edad de persona mayor:44 ID: 9, Edad: 8545 ID y edad de persona menor:46 ID: 6, Edad: 1947 [{'ID': 9, 'Edad': 85}, {'ID': 7, 'Edad': 77}, {'ID': 4, 'Edad': 74}, {'ID': 8, 'Edad': 62}, {'ID': 2, 'Edad': 54}, {'ID': 1, 'Edad': 51}, {'ID': 3, 'Edad': 31}, {'ID': 10, 'Edad': 29}, {'ID': 5, 'Edad': 21}, {'ID': 6, 'Edad': 19}]48 '''49 sorted_list = sorted(list_dicts, key=itemgetter('Edad'), reverse=True)50 print(f'ID y edad de persona mayor:\nID: {sorted_list[0]["ID"]}, Edad: {sorted_list[0]["Edad"]}')51 print(f'ID y edad de persona menor:\nID: {sorted_list[-1]["ID"]}, Edad: {sorted_list[-1]["Edad"]}')52 return sorted_list53if __name__ == '__main__':54 import doctest...

Full Screen

Full Screen

PersonWorkDict.py

Source:PersonWorkDict.py Github

copy

Full Screen

...12def test_PersonWorkDict():13 myobj = PersonWorkDict(12,4)14 print(myobj.PID)15 print(myobj.WID)16def test_list_of_dicts():17 mylist = []18 myobj1 = [12,4]19 myobj2 = [1,2]20 myobj3 = [1,2]21 22 mylist.append([12,4])23 mylist.append([1,2])24 print(mylist)25 mylist.remove([1,2])26 print(mylist) 27if __name__ == "__main__":28 #test_PersonWorkDict()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run assertpy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful