Python Dictionary - Constructor

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
#an empty dictionary and populates it

# Create an empty dictionary using the constructor
colors = dict();

# Add RGB values of few colors
colors["Yellow"]     = (255 , 255, 102);
colors["Orange"]     = (255, 204, 0);
colors["Magenta"]     = (255, 153, 255);
colors["Pink"]         = (255,102,204);
colors["Turquoise"] = (102,255,153);

# Print the colors dictionary
print("Colors:");
print(colors);

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
# pairs to an empty dictionary instance through
# keyword arguments

# Creation of an empty dictionary
grayColors = dict();

# Add gray1
hexVal = "#898989";
grayColors.update(Gray1=hexVal);

# Add gray2
hexVal = "#dcdcdc";
grayColors.update(Gray2=hexVal);

# Add gray3
hexVal = "#cbcbcb";
grayColors.update(Gray3=hexVal);

print("Gray colours:");
print(grayColors);

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)}

 


Copyright 2023 © pythontic.com