Overview:
- By calling the constructor function of the dictionary dict(), an empty dictionary object is created. Elements can be added using the square bracket notation(subscript notation) and assignment operator.
e.g., dict_object["key"] = value
- The dictionary elements can be added by calling the update() method as well. The update() method is versatile in terms of its parameters. If a dictionary is passed as a parameter, the values of the dictionary is replaced with the new values from the dictionary parameter, for the common keys present.To the update()method the key-value pairs can be passed as a tuple or as keyword arguments.
Example1 - Add key-value pairs to Python dictionary using square bracket notation:
#Example Python program that creates # Create an empty dictionary using the constructor # Add RGB values of few colors # Print the colors dictionary
|
Output:
Colors: {'Yellow': (255, 255, 102), 'Orange': (255, 204, 0), 'Magenta': (255, 153, 255), 'Pink': (255, 102, 204), 'Turquoise': (102, 255, 153)} |
Example 2 - Add key-value pairs to Python dictionary using keyword arguments:
# Example Python program that adds key-value # Creation of an empty dictionary # Add gray1 # Add gray2 # Add gray3 print("Gray colours:");
|
Output:
Gray colours: {'Gray1': '#898989', 'Gray2': '#dcdcdc', 'Gray3': '#cbcbcb'} |
Example 3 - Update an empty dictionary with the values from another dictionary:
# Example python program that populates # an empty Python dictionary using key-value pairs # from an another Python dictionary object colors = {"Cyan": (102, 255, 255), "Sky blue":(0, 204, 255), "Yellow green":(204, 255,0)}; copiedColors = dict(); copiedColors.update(colors); print("Copied colors:"); print(copiedColors); |
Output:
Copied colors: {'Cyan': (102, 255, 255), 'Sky blue': (0, 204, 255), 'Yellow green': (204, 255, 0)} |