Python

Python dict : Create and Initialize

arage.com@gmail.com

A Python dictionary is a data structure that efficiently retrieves values based on keys. Any hashable object can be used as a key, with strings, integers, and tuples being common. The main advantages of a dictionary are as follows:

  • Fast lookups
    • Retrieving values by using keys is very fast.
  • Efficient memory usage
    • Dictionaries are space-efficient and suitable for storing large amounts of data.
  • Uniqueness of keys
    • You can’t have multiple elements with the same key.

There are several ways to initialize a dictionary.

Basic Methods to Initialize Python Dictionaries

1# Method 1: Using curly braces
2my_dict = {'apple': 1, 'banana': 2, 'orange': 3}
3
4# Method 2: Using the dict function
5my_dict = dict(apple=1, banana=2, orange=3)
6
7# Method 3: Using tuples inside the dict function
8my_dict = dict([('apple', 1), ('banana', 2), ('orange', 3)])

Creating and Initializing Empty Dictionaries

1# Method 1: Using curly braces
2my_dict = {}
3
4# Method 2: Using the dict function
5my_dict = dict()

How to Initialize Using Dictionary Comprehension

1fruits = ['apple', 'banana', 'orange']
2numbers = [1, 2, 3]
3
4# Using dictionary comprehension
5my_dict = {k: v for k, v in zip(fruits, numbers)}
6
7print(my_dict)  # Prints: {'apple': 1, 'banana': 2, 'orange': 3}
記事URLをコピーしました