Dictionaries in Python

A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable.

Example: Here, the data is stored in key: value pairs in dictionaries, which makes it easier to find values.

Python 

d = {1: 'Codes', 2: 'For', 3: 'Codes'}
print(d)
Output

{1: 'Codes', 2: 'For', 3: 'Codes'}

How to Create a Dictionary

In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated by a ‘comma’.


Python

# create dictionary using { }
d1 = {1: 'Codes', 2: 'For', 3: 'Codes'}
print(d1)

# create dictionary using dict() constructor
d2 = dict(a = "Codes", b = "for", c = "Codes")
print(d2)
Output

{1: 'Codes', 2: 'For', 3: 'Codes'}
{'a': 'Codes', 'b': 'for', 'c': 'Codes'}
  • From Python 3.7 Version onward, Python dictionary is Ordered.
  • Dictionary keys are case sensitive: the same name but distinct cases of Key will be treated distinctly.
  • Keys must be immutable: This means keys can be strings, numbers, or tuples but not lists.
  • Keys must be unique: Duplicate keys are not allowed, and any duplicate key will overwrite the previous value.
  • Dictionary internally uses Hashing. Hence, operations similar as search, insert, delete can be performed in Constant Time.

Python dictionaries are essential for efficient data mapping and manipulation in programming. To deepen your understanding of dictionaries and explore advanced techniques in data handling. This content tries to cover everything from basic dictionary operations to advanced data processing methods, empowering you to become proficient in Python programming and data analysis.

Accessing Dictionary Items

We can access a value from a dictionary by using the key within square brackets orget()method.


Python 

d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }
# Access using key
print(d["name"])

# Access using get()
print(d.get("name"))  
Output

Alice
Alice

Adding and Updating Dictionary Items

We can add new key-value pairs or update existing keys by using assignment.


Python 

d = {1: 'Codes', 2: 'For', 3: 'Codes'}
# Adding a new key-value pair
d["age"] = 22

# Updating an existing value
d[1] = "Python dict"

print(d)
Output

{1: 'Python dict', 2: 'For', 3: 'Codes', 'age': 22}

Removing Dictionary Items

We can remove items from dictionary using the following methods:

  • del: Removes an item by key.
  • pop(): Removes an item by key and returns its value.
  • clear(): Empties the dictionary.
  • popitem(): Removes and returns the last key-value pair.


Python 

d = {1: 'Codes', 2: 'For', 3: 'Codes', 'age':22}
# Using del to remove an item
del d["age"]
print(d)

# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)

# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")

# Clear all items from the dictionary
d.clear()
print(d)
Output

{1: 'Codes', 2: 'For', 3: 'Codes'}
codes
Key: 3, Value: Codes
{}

Iterating Through a Dictionary

We can iterate over keys [using keys() method] , values [using values() method] or both [using item() method] with a for loop.

Python 

d = {1: 'Codes', 2: 'For', 'age':22}
# Iterate over keys
for key in d:
    print(key)

# Iterate over values
for value in d.values():
    print(value)

# Iterate over key-value pairs
for key, value in d.items():
    print(f"{key}: {value}")
Output

1
2
age
Codes
For
22
1: Codes
2: For
age: 22

Nested Dictionaries

Example of Nested Dictionary:

Python 

    d = {1: 'Codes', 2: 'For',
                     3: {'A': 'Welcome', 'B': 'To', 'C': 'Codes'}}

print(d)
Output

{1: 'Codes', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Codes'}}

Python Dictionary – FAQs

How to use dictionaries in Python?

Dictionaries in Python are getting used to store key-value pairs. They are unordered, mutable, and can contain any Python objects when values.

# Creating a dictionary
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
# Accessing values by keys
print(my_dict[‘key1’]) # Output: value1

# Modifying values
my_dict[‘key2’] = ‘new_value’
# Adding new key-value pairs
my_dict[‘key3’] = ‘value3’
# Removing a key-value pair
del my_dict[‘key1’]

How to print dictionaries in Python?

You can use print() to display the contents of a dictionary. You can print the entire dictionary or specific elements by accessing keys or values.

my_dict = {‘name’: ‘Alice’, ‘age’: 30}
# Printing the entire dictionary
print(my_dict)
# Printing specific elements
print(my_dict[‘name’]) # Output: Alice

How to declare a dictionary in Python?

You can declare a dictionary by enclosing key-value pairs within curly braces {}.

# Empty dictionary
empty_dict = {}
# Dictionary with initial values
my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}

What are dictionary keys and values in Python?

In a dictionary, keys are unique identifiers that are getting used to access values. Values are the data associated with those keys.

my_dict = {‘name’: ‘Alice’, ‘age’: 30}
# Accessing keys and values
print(my_dict.keys()) # Output: dict_keys([‘name’, ‘age’])
print(my_dict.values()) # Output: dict_values([‘Alice’, 30])

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the