How are dictionaries created in Python?

QuestionsQuestions8 SkillsProPython Data StructuresSep, 10 2025
0123

Dictionaries in Python can be created in several ways. Here are some common methods:

  1. Using curly braces {}:

    my_dict = {
        'key1': 'value1',
        'key2': 'value2',
        'key3': 'value3'
    }
  2. Using the dict() constructor:

    my_dict = dict(key1='value1', key2='value2', key3='value3')
  3. Using a list of tuples:

    my_dict = dict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
  4. Using dictionary comprehension:

    my_dict = {x: x**2 for x in range(5)}  # Creates a dictionary with keys 0-4 and values as their squares
  5. From another dictionary:

    original_dict = {'key1': 'value1', 'key2': 'value2'}
    new_dict = dict(original_dict)  # Creates a copy of the original dictionary

You can access values in a dictionary using their keys, and you can also add or update key-value pairs easily.

0 Comments

no data
Be the first to share your comment!