Dictionaries are a fundamental data structure in Python, providing a way to store key-value pairs. Unlike lists, which are indexed numerically, dictionaries use keys to access values. Keys can be numbers, strings, or even tuples (if they are immutable). Dictionaries are unordered collections in Python versions before 3.7; starting from Python 3.7, dictionaries maintain insertion order.
Creating a Dictionary
An empty dictionary can be created using {} or the dict() constructor:
# Creating an empty dictionary
dic = {}
# Creating a dictionary with key-value pairs
dic = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
Accessing and Modifying Dictionary Elements
You can access values using their keys, add new key-value pairs, and delete keys:
# Accessing values
print(dic['one']) # Output: 1
# Adding a new key-value pair
dic['six'] = 6
print(dic) # Output: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
# Deleting a key-value pair
del dic['five']
print(dic) # Output: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'six': 6}
Checking for Key Existence
To check if a key exists in a dictionary, use the in keyword:
print('one' in dic) # Output: True
print('seven' in dic) # Output: False
Retrieving Keys and Values
Python provides methods to get all keys, values, or key-value pairs:
# Getting all keys
print(list(dic.keys())) # Output: ['one', 'two', 'three', 'four', 'six']
# Getting all values
print(list(dic.values())) # Output: [1, 2, 3, 4, 6]
# Getting key-value pairs
print(list(dic.items())) # Output: [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('six', 6)]
Creating a Dictionary from a List of Tuples
A dictionary can be created from a list of tuples, where each tuple contains a key-value pair:
a = [('aass', 23), ('iiii', 56), ('dftj', 38)]
dic_from_list = dict(a)
print(dic_from_list) # Output: {'aass': 23, 'iiii': 56, 'dftj': 38}
Using dict() with Keyword Arguments
You can also create a dictionary using keyword arguments:
d = dict(jhjkhk=433, jkhjkhk=3434, iuijmkm=344343)
print(d) # Output: {'jhjkhk': 433, 'jkhjkhk': 3434, 'iuijmkm': 344343}
Dictionary Methods
Here are some useful dictionary methods:
# Removing a key and returning its value
value = dic.pop('one', 'Key not found')
print(value) # Output: 1
print(dic) # Output: {'two': 2, 'three': 3, 'four': 4, 'six': 6}
# Merging dictionaries
other_dic = {'seven': 7, 'eight': 8}
dic.update(other_dic)
print(dic) # Output: {'two': 2, 'three': 3, 'four': 4, 'six': 6, 'seven': 7, 'eight': 8}
Python 3 Enhancements for Dictionaries
- Dictionary Comprehensions: You can create dictionaries using comprehensions:
squares = {x: x**2 for x in range(5)} print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} - The
defaultdictfromcollectionsmodule: Provides a default value for missing keys:from collections import defaultdict dd = defaultdict(int) # Default value of int is 0 print(dd['missing_key']) # Output: 0 - The
Counterfromcollectionsmodule: Used to count occurrences in an iterable:from collections import Counter counter = Counter("banana") print(counter) # Output: {'b': 1, 'a': 3, 'n': 2}
Dictionaries are one of the most powerful and versatile data structures in Python. Understanding their operations and enhancements helps in writing more efficient and readable code.