Python Web-L06 (Creating dictionary)

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 comprehension 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 lists keys = ['a', 'b', 'c'] values = [1, 2, 3] # Dictionary comprehension my_dict = {k: v for k, v in zip(keys, values)} print(my_dict) # Output:{'a': 1, 'b': 2, 'c': 3} #Creating a dictionary from two lists (lack of 1 item) #Two lists keys = ['a', 'b'] values = [1, 2, 3] # Dictionary comprehension my_dict = {k: v for k, v in zip(keys, values)} print(my_dict) # Output:{'a': 1, 'b': 2, 'c': 3} # Filtering items in a dictionary # Original 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} filter_list_key = [k for k, v in original_dict.items() if v > 2] filter_list_value = [v for k, v in original_dict.items() if v > 2] print(filtered_dict,filter_list_key,filter_list_value) # Transforming keys and values # Original dictionary original_dict = {'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 from a range # Dictionary comprehension with range; key can include value 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 # x : {y: x * y for y in range(1, 4)} -> return value 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, 3: 6}, 3: {1: 3, 2: 6, 3: 9}} # Swapping keys and values # Original dictionary original_dict = {'a': 1, 'b': 2, 'c': 3} # Dictionary comprehension to swap keys and values swapped_dict = {v: k for k, v in original_dict.items()} 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 comprehension with conditional logic my_dict = {k: ('even' if ord(k) % 2 == 0 else 'odd') for k in keys} print(my_dict) # Output: {'a': 'odd', 'b': 'even', 'c': 'odd', 'd': 'even'}
Editor Settings
Theme
Key bindings
Full width
Lines