SetDefault and Defaultdict
#SetDefaultPeriodic_table = {'hydrogen': 1,'Helium': 2}carbon= Periodic_table.setdefault ('Carbon', 12)Print(carbon)Print(periodic_table) Helium= Periodic_table.setdefault ('Helium', 947)Print(helium)Print(periodic_table)#defaultdictPrint(int ())) fromCollectionsImportDefaultdictperiodic_table2=defaultdict (int) periodic_table2['hydrogen'] = 1Print(periodic_table2[' Lead'])Print(Periodic_table2)defNo_idea ():return 'Hub?'Bestiary=defaultdict (No_idea) bestiary['A'] ='Abominable Snowman'Print(bestiary['B'])
Output
12{'Carbon': 12,'Helium': 2,'hydrogen': 1}2{'Carbon': 12,'Helium': 2,'hydrogen': 1}00defaultdict (<class 'int', {' Lead': 0,'hydrogen': 1}) Hub?
Pprint
Itertools
ImportItertoolscount=0 forIteminchItertools.chain ([1, 2, 3], ['a','b']): Count+ = 1Print('Count', Count)Print(item)Print('-------------') Count=0 forIteminchItertools.cycle ([1, 2]): Count+ = 1Print('Count', Count)ifCount < 5: Print(item)Else: BreakPrint('-------------')#cumulative values, default cumulative, and forIteminchItertools.accumulate ([1, 2, 3, 4]): Print(item)Print('-------------')defMultiply (A, b):returnAb forIteminchItertools.accumulate ([1, 2, 3, 4], multiply):Print(item)
Output
count 4 5 b------------- 5-------------13610-------------12624
SetDefault and Defaultdict