Dictionary in Python
In Python, dictionaries are a type of data structure that store key-value pairs. They are unordered, mutable, and indexed by keys, which can be of any immutable data type (like strings, numbers, or tuples). Values associated with keys can be of any data type.
Creating a Dictionary in Python
You can create dictionaries using curly braces { }
, with each key-value pair separated by a colon :
. The keys in a dictionary act as indexes, similar to how lists are indexed by numbers. However, unlike lists, dictionaries are indexed by keys, which can be any immutable data type, such as strings or numbers. Dictionary keys are case-sensitive.
Syntax for Creating a Dictionary
The basic syntax to create a dictionary is:
Here's a breakdown:
- Opening Curly Braces
{
: Used to start the dictionary. - Closing Curly Braces
}
: Used to end the dictionary. - Comma-Separated List: Each key-value pair is separated by a comma
,
. - Key-Value Pair: Each key is separated from its value by a colon
:
.
Example of Creating a Dictionary
In this example:
- The keys are
"r"
,"y"
,"o"
,"b"
, and"g"
. - The values associated with these keys are
"red"
,"yellow"
,"orange"
,"black"
, and"green"
.
Characteristics of Dictionary Keys
- Immutable: Dictionary keys must be of an immutable data type, like strings or numbers. Lists cannot be used as keys because they can be modified in place.
- Unique: Duplicate keys are not allowed in a dictionary. If you try to use a key that already exists, the old value will be overwritten with the new one.
Example with Mixed Data Types
Here, mixed_dict
contains keys and values of different types, showing that Python dictionaries can store a variety of data types.
Creating an Empty Dictionary
You can create an empty dictionary by using a pair of curly braces without including any key-value pairs.
Order of Key-Value Pairs
In dictionaries, the order of key-value pairs does not matter. Python ensures that as long as the keys and values are the same, the order won't affect equality.
In this example, even though the order of key-value pairs is different, both dictionaries are considered equal.
Prior to Python 3.6, dictionaries were unordered collections. However, starting from Python 3.6, dictionaries maintain the insertion order of key-value pairs, meaning that they remember the order in which items were added.
Accessing and Modifying Key-Value Pairs in Dictionaries
In Python, dictionaries allow you to store, access, and modify data using key-value pairs. Each key in a dictionary is associated with a specific value, and you can retrieve or modify these values by referencing their keys.
Accessing Values in a Dictionary
To access the value associated with a specific key in a dictionary, you use square brackets []
containing the key. This key is used to locate the corresponding value in the dictionary.
Syntax:
Example:
In this example, the key "Toyota Corolla"
is used to retrieve the value 1966
.
Modifying Values and Adding New Key-Value Pairs
Dictionaries are mutable, which means you can modify the values of existing keys or add new key-value pairs. To update a value, you simply assign a new value to the key. If the key does not exist in the dictionary, a new key-value pair is added.
Syntax:
Example:
After executing the above code:
- The value for
"Tesla Model 3"
is updated from2017
to2024
. - A new key
"Honda Civic"
is added with the value1972
.
Example with Updated Dictionary
Handling Non-Existent Keys
If you try to access a key that doesn't exist in the dictionary, Python will raise a KeyError
.
Example:
To avoid this, you can use the in
operator to check if a key exists in the dictionary before trying to access it.
Example:
Checking for Key Presence
You can check whether a key is present in a dictionary using the in
and not in
membership operators, which return True
or False
.
Example:
In this example, since "spring"
is not a key in the clothes
dictionary, the output is False
for "spring" in
clothes and True
for "spring" not in
clothes.
Creating Dictionaries with the dict()
Function
The dict()
function is a built-in function in Python used to create dictionaries. This function can be used with keyword arguments or iterables.
Syntax:
Example:
Here, one=1
, two=2
, and three=3
are converted into key-value pairs within the numbers
dictionary.
Creating a Dictionary from Iterables
You can also create dictionaries from iterables, like a list of tuples where each tuple contains a key-value pair.
Syntax:
Example:
The dict()
function takes the list of tuples and converts them into a dictionary.
Built-In Functions Used on Dictionaries
Python provides several built-in functions that can be used to operate on dictionaries. These functions help in performing various tasks, such as finding the length of a dictionary, checking if all or any keys evaluate to True
, and sorting the dictionary based on keys or values.
Function | Description |
---|---|
len() | Returns the number of items (key-value pairs) in the dictionary. |
all() | Returns True if all keys in the dictionary are True ; otherwise, returns False . |
any() | Returns True if any key in the dictionary is True ; otherwise, returns False . |
sorted() | Returns a sorted list of keys in the dictionary by default. Can also sort by values or items (key-value pairs). |
Examples of Using Built-In Functions on Dictionaries
Let's go through some examples to understand how these functions work.
-
len()
The
len()
function returns the number of key-value pairs in the dictionary. -
all()
The
all()
function returnsTrue
if all keys in the dictionary evaluate toTrue
. If any key isFalse
, it returnsFalse
.In the first example, since
0
is consideredFalse
, all(all_dict_func) returnsFalse
. In the second example, since both keys are non-zero (and thusTrue
), all(all_dict_func) returnsTrue
. -
any()
The
any()
function returnsTrue
if at least one key in the dictionary evaluates toTrue
. If all keys areFalse
, it returnsFalse
.Here, since
2
isTrue
, any(any_dict_func) returnsTrue
. -
sorted()
The
sorted()
function returns a sorted list of the dictionary's keys by default. You can also sort by values or items (key-value pairs).Sort by Keys:
In the above examples:
sorted()
returns a list of sorted keys, values, or key-value pairs based on the specified criteria.- By default, sorting is done in ascending order, but you can reverse it by using
reverse=True
.
Sort by Values
The
sorted()
function then sorts these values in ascending order, which means from the smallest to the largest year.Sort by Items
The
sorted()
function sorts these tuples by the first element of each tuple (the key, which is the car model name) in alphabetical order.
Dictionary Methods
Dictionaries in Python offer a variety of methods to manage and manipulate the key-value pairs they contain. These methods allow you to add, update, remove, and access data in a dictionary efficiently.
Various Dictionary Methods
Method | Syntax | Description |
---|---|---|
clear() | dictionary_name.clear() | Removes all key-value pairs from the dictionary. |
fromkeys() | dictionary_name.fromkeys(seq[, value]) | Creates a new dictionary from a sequence of elements with a specified value. |
get() | dictionary_name.get(key[, default]) | Returns the value associated with a key, or the default value if the key is not found. |
items() | dictionary_name.items() | Returns a view object containing key-value pairs as tuples. |
keys() | dictionary_name.keys() | Returns a view object containing all the keys in the dictionary. |
pop() | dictionary_name.pop(key[, default]) | Removes a key from the dictionary and returns its value. If the key is not found, returns the default value or raises a KeyError . |
popitem() | dictionary_name.popitem() | Removes and returns an arbitrary key-value pair from the dictionary. If the dictionary is empty, raises a KeyError . |
setdefault() | dictionary_name.setdefault(key[, default]) | Returns the value of a key if it exists, otherwise inserts the key with a specified default value. |
update() | dictionary_name.update([other]) | Updates the dictionary with key-value pairs from another dictionary or iterable. |
values() | dictionary_name.values() | Returns a view object containing all the values in the dictionary. |
Examples of Using Dictionary Methods
-
clear()
Theclear()
method removes all key-value pairs from the dictionary. -
fromkeys()
The
fromkeys()
method creates a new dictionary from a sequence of keys, each associated with a specified value. -
get()
The
get()
method retrieves the value of a key if it exists, or returns a default value if the key is not found. -
items()
,keys()
, andvalues()
These methods return view objects representing the dictionary's items (key-value pairs), keys, and values.
-
pop()
The
pop()
method removes a specified key and returns its value. -
popitem()
The
popitem()
method removes and returns an arbitrary (key, value) pair from the dictionary. -
setdefault()
The
setdefault()
method returns the value of a key if it exists. If the key does not exist, it inserts the key with a specified default value. -
update()
The
update()
method adds key-value pairs from another dictionary or iterable to the current dictionary.
Populating a Dictionary
One common way to populate a dictionary is to start with an empty dictionary {}
, and then use the update()
method to add key-value pairs. If the key does not exist, it will be created automatically.
In this example, an empty dictionary countries
is populated with key-value pairs using the update()
function. Each update()
call adds a new key-value pair to the dictionary.
Iterating Over Dictionaries
You can use a for
loop to iterate over keys, values, or key-value pairs in a dictionary. By default, iterating over a dictionary with a for
loop will iterate over its keys. To iterate over values, use the values()
method, and to iterate over key-value pairs, use the items()
method.
In this example, the loop iterates over the keys, values, and key-value pairs of the countries
dictionary.
Output
The del Statement
The del
statement is used to delete a key-value pair from a dictionary. The syntax is straightforward:
Here's an example:
In this example, the del
statement removes the key-value pair "c": "cougar"
from the animals
dictionary.
Last updated on -