Day 13 -  Part C

Run Settings
LanguagePython
Language Version
Run Command
#Creating a dictionary from a list of tuples #list of tuples items = [('a',1), ('b', 2), ('c', 3)] # Dictionary compreshension my_dict = {key: value for (key, value) in items} print(my_dict) # Output : {'a' : 1, 'b' : 2, 'c' :3} # Creating a dictionary from two lists # Two list keys = ['a', 'b', 'c'] values = [1,2,3] #Dictionary comprehension my_dict = {k : v for k, v in zip(keys, values)} # zip is combine two list in same position of each element. #If the number of elements are different, it will combine according the short lenght list #output : {'a': 1, 'b':2, 'c':3} #Filtering items in a dictionary #Orginal dictionary original_dict = {'a': 1, 'b':2, 'c':3, 'd':4} #Dictionary comprehension with a condition filtered_dict = {k : v for k, v in original_dict.items() if v < 2} print(filtered_dict) #output : {'c': 3, 'd':4} #transforming keys and values #Original dictionary original_dic = {'a':1, 'b':2, 'c':3} #Dictionary comprehension with transformation transformed_dict={k.upper(): v*2 for k,v in original_dict.items()} print(transformed_dict) #output {'A':2,'b':4, 'c':6} # Creating a dictionary form a range #Dictionary comprehension with range my_dict = {x:x**2 for x in range(5)} print(my_dict) #Output : {0:0, 1:1, 2:4, 3:9, 4:16} #Nested dictionary comprehension #Nested dictionary comprehension nested_dict = {x:{y:x*y for y in range(1,4)} for x in range(1,4)} print(nested_dict) #Output: {1:{1:1,2:2,3:3}, 2:{1:2,2:4, refer print(swapped_dict) #Output: {1:'a', 2:'b', 3:'c'} #Creating a dictionary with conditional logic #List of keys keys = ['a', 'b','c','d'] # Dictionary compreshension with conditinal logic my_dict = {k:('even' if ord(k) % 2 ==0 else 'odd') for k in keys} my_dict = {k:('odd' if ord(k)%2 else 'even') for k in keys # this statement same as line 58 print(my_dict) #Output: {'a':'odd', 'b':'even', 'c': 'odd', 'd':'even'} print(my_dict)
Editor Settings
Theme
Key bindings
Full width
Lines