what is the syntax to create a dictionary?

1 day ago 1
Nature

To create a dictionary in Python, you can use either curly braces {} with key-value pairs inside or the built-in dict() function. Here is the syntax and examples:

Using Curly Braces {}

  • Basic syntax:

    python
    
    dictionary_name = {key1: value1, key2: value2, ...}
    
  • Example:

    python
    
    my_dict = {"name": "Alice", "age": 30, "role": "Engineer"}
    
  • To create an empty dictionary:

    python
    
    my_dict = {}
    

Keys and values are separated by a colon :, and each key-value pair is separated by a comma. Keys must be immutable and hashable types like strings, numbers, or tuples

Using the dict() Function

  • You can create a dictionary by passing key-value pairs as keyword arguments:

    python
    
    my_dict = dict(name="Alice", age=30, role="Engineer")
    
  • Or by passing a list of tuples:

    python
    
    pairs = [("name", "Bob"), ("age", 25), ("city", "Los Angeles")]
    my_dict = dict(pairs)
    
  • To create an empty dictionary:

    python
    
    my_dict = dict()
    

This method is useful for dynamic dictionary creation or converting sequences to dictionaries

Summary

Method| Syntax Example| Notes
---|---|---
Curly braces| my_dict = {"key": "value", "key2": "value2"}| Most common and concise
Empty dictionary| my_dict = {}|
dict() with kwargs| my_dict = dict(key="value", key2="value2")| Keys must be valid Python identifiers
dict() with tuples| my_dict = dict([("key", "value"), ("key2", 2)])| Useful for converting sequences
Empty dictionary| my_dict = dict()|

This covers the standard ways to create dictionaries in Python