What is a Python dictionary?
A dictionary is an associative array, containing a collection of keys and their associated values.
Python dictionaries are constructed using curly brackets {}
, with a colon separating the key from its value {key:value, key:value}
. Each key-value pair is separated by a comma.
An example of a Python dictionary:
dict = { "key1":"value1", "key2":"value2", "key3":"value3" }
This guide will walk you through how to use Python dictionaries, including their creation, modification, and the most efficient way to iterate over their elements.
- Create a dictionary
- Add items to a dictionary
- Read from a dictionary
- Update a dictionary
- Delete from a dictionary
- Testing dictionary membership
- Dictionary operators
- Built-in functions
- Dictionary methods
- Dictionary equality
- Nested dictionaries
Create a Dictionary
A Python dictionary can be created in two ways:
- Assignment
- Using the
dict
constructor
# Create an empty dictionary dict = {} # Create a populated dictionary dict = { "key1":"value1", "key2":"value2" } # Print the dictionary print(dict)
Output:
{'key1': 'value1', 'key2': 'value2'}
You can also create a dictionary with different data types and object types as the key:
# Using tuples as keys tupleDict = { (1,2,3):'value1', (4,5,6):'value2' } print(tupleDict) # Using decimals as keys decimalDict = { 3.142:'value1', 3.143:'value3' } print(decimalDict) # Using strings as keys stringDict = { "key1":"value1", "key2":"value2", "key3":"value3" } print(stringDict)
Output:
{(1, 2, 3): 'value1', (4, 5, 6): 'value2'}
{3.142: 'value1', 3.143: 'value3'}
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
2. Using the dict
constructor
# Create the dictionary dict1 = dict({"a":1, "b":2, "c":3}) print("dict1 = {}".format(dict1))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3}
However, there are a few caveats worth bearing in mind when creating a dictionary:
- Only immutable data types can be used as keys. This means you can’t use a dictionary as the key of another dictionary.
- Each key must be unique. If you have duplicate keys, the value of the most recent one to be read will overwrite any previous value for that key.
Read from a Dictionary
Dictionaries are accessed by specifying the key name inside square brackets.
# Access the dictionary item value that has a key of 'cat' dict = { "cat":"cat_value", "dog":"dog_value" } dict["cat"] print(dict["cat"])
Output:
cat_value
However, if the key does not exist in the dictionary, this will return a KeyError.
If you never want to return a KeyError, even when the key does not exist in the dictionary, you can use the get()
method:
# Get the value associated with the 'cat' key. dict.get("cat")
Output:
'cat_value'
Iterating through Python dictionaries
If you want to iterate through the key-value pairs in a Python dictionary, you have three options.
for
loopitems()
,keys()
andvalues()
- Dictionary comprehension
Option 1: For loop
# Create the dictionary dict = { "cat":"cat_value", "dog":"dog_value" } # For loop: Access the key names for x in dict: print(x)
Output:
cat
dog
# For loop: Access the values for x in dict.values(): print(x)
Output:
cat_value
dog_value
# For loop: Access key names and their associated values for x, y in dict.items(): print(x, y)
Output:
cat cat_value
dog dog_value
Option 2: keys() and values()
# Create the dictionary dict = { "cat":"cat_value", "dog":"dog_value" } # iterkeys() for key in dict.keys(): print(key)
Output:
cat
dog
# iterkeys() for val in dict.values(): print(val)
Output:
cat_value
dog_value
Option 3: Dictionary comprehension
A simple guide for Python dictionary comprehension is: dict_name = {key:value for (key, value) in dictionary.items()}
.
Example 1: Updating dictionary keys using comprehension
# Create a dictionary dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Update the key values dict1 = {k:v*2 for (k, v) in dict1.items()} print("dict1 = {}".format(dict1))
Output:
dict1 = {'a': 2, 'b': 4, 'c': 6, 'd': 8}
Example 2: Updating dictionary keys using comprehension
# Create a dictionary dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Update the keys dict1 = {k*2:v for (k, v) in dict1.items()} print("dict1 = {}".format(dict1))
Output:
dict1 = {'aa': 1, 'bb': 2, 'cc': 3, 'dd': 4}
Example 3: Dictionary comprehension including ‘if’ conditional
# Create a dictionary dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Update the keys if the key value is an even number dict1 = {k*2:v for (k, v) in dict1.items() if v%2 == 0} print("dict1 = {}".format(dict1))
Output:
dict1 = {'bb': 2, 'dd': 4}
Example 4: Dictionary comprehension including ‘if..else’ conditional
# Create a dictionary dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Update the keys if the key value is an even number dict1 = {k:('Even' if v%2 == 0 else 'Odd') for (k, v) in dict1.items()} print("dict1 = {}".format(dict1))
Output:
dict1 = {'a': 'Odd', 'b': 'Even', 'c': 'Odd', 'd': 'Even'}
Update a Dictionary
To update a specific dictionary item, you can refer to it by its key name, then specify the new value you would like to assign.
# Create a dictionary dict = { "key1":"value1", "key2":"value2", "key3":"value3" } # Update the value for 'key1' to be 'value4' dict["key1"] = "value4" print(dict)
Output:
{'key1': 'value4', 'key2': 'value2', 'key3': 'value3'}
Delete from a Dictionary
There are 3 main ways to delete items from a dictionary, or to delete the dictionary object itself:
- Using the
del
keyword - Using the
pop(key[, default])
method - Using the
clear()
method
If you try to delete a key that doesn’t exist in the dictionary using del
, or pop()
without the default, a KeyError will be thrown. If a default value is passed to the pop()
method, the default value will be returned instead.
All three options will mutate the dictionary in-place, rather than return a new dictionary.
If you want the existing dictionary to stay the same, but create a new version with some items deleted, you’ll need to make a copy of the dictionary first. The dict()
constructor can be used to make a shallow copy, or the copy()
method used to create a deep copy.
# Create a dictionary dict1 = {"val1":"key1", "val2":"key2"} print("dict1 = {}".format(dict1)) # Use the 'del' keyword to delete element with key of 'val1' del dict1["val1"] print("\ndict1 after del dict1['val1'] = {}".format(dict1)) # Now delete the dictionary object itself using 'del' del dict1 print("\ndict1 after 'del dict1' = {}".format(dict1))
Output:
dict1 = {'val1': 'key1', 'val2': 'key2'}
dict1 after del dict1['val1'] = {'val2': 'key2'}
Traceback (most recent call last):
File "main.py", line 11, in
print("\ndict1 after 'del dict1'\n{}".format(dict1))
NameError: name 'dict1' is not defined
2. Using the pop() method
# Create a dictionary dict1 = {"val1":"key1", "val2":"key2", "val3":"key3"} print("dict1 = {}".format(dict1)) # Use pop('val1') to remove an element by its key dict1.pop("val1") print("dict1 after pop('val1') = {}".format(dict1)) # Attempt to pop() a key that doesn't exist, to show default returned print("dict1.pop('val9', 6) = {}".format(dict1.pop("val9", 6))) # Attempt to use pop() witout passing any parameters dict1.pop()
Output:
dict1 = {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
dict1 after pop('val1') = {'val2': 'key2', 'val3': 'key3'}
dict1.pop('val9', 6) = 6
Traceback (most recent call last):
File "main.py", line 13, in
dict1.pop()
TypeError: pop expected at least 1 arguments, got 0
3. Using the clear() method
# Create a dictionary dict1 = {"val1":"key1", "val2":"key2", "val3":"key3"} print("dict1 = {}".format(dict1)) # Use clear() to delete all elements in dict1 dict1.clear() print("dict1 after dict1.clear() = {}".format(dict1))
Output:
dict1 = {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
dict1 after dict1.clear() = {}
Testing Dictionary Membership
To check if a key value exists in a dictionary, you can use the in
and not in
keywords. Each returns a Boolean.
# Create a dictionary dict1 = {"a":1, "b":2, "c":3, "d":4} print("dict1 = {}".format(dict1)) # Test whether dict1 contains 'a' by using its key print("'a' in dict1 = {}".format("a" in dict1)) # Test whether dict1 contains 'a' by using its value (1) print("1 in dict1 = {}".format(1 in dict1)) # Use 'not in' to check if dict1 keys contains 'e' print("'e' not in dict1 = {}".format("e" not in dict1))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
'a' in dict1 = True
1 in dict1 = False
'e' not in dict1 = True
Dictionary Operators
Python dictionaries cannot be used with operators in the same way lists and strings can. Attempting to concatenate two dictionaries using the +
operator will result in a TypeError. If you need to merge two dictionaries, the update()
method should be used instead. E.g. dict1.update(dict2)
.
# Create two dictionaries dict1 = {"a":1, "b":2, "c":3, "d":4} dict2 = {"e":5, "f":6} # Attempt to concatenate dict1 and dict2 using the '+' operator dict1 + dict2
Output:
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
Using the update() method
# Create two dictionaries dict1 = {"a":1, "b":2, "c":3, "d":4} dict2 = {"e":5, "f":6} # Attempt to combine dict1 and dict2 dict1.update(dict2) print("dict1 after dict1.update(dict2) = \n{}".format(dict1))
Output:
dict1 after dict1.update(dict2) =
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
Built-in Functions
As with lists, Python dictionaries can be used with a variety of in-built functions. This includes len()
, max()
, min()
and sorted()
.
Applying the len()
function to a Python dictionary will return how many key-value pairs it contains.
# Create a dictionary dict1 = {"b":2, "a":1, "d":4, "c":3} print("dict1 = {}".format(dict1)) # Use len() to return how many key-value pairs dict1 contains print("len(dict1) = {}".format(len(dict1)))
Output:
dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
len(dict1) = 4
max()
Returns the maximum key value from a dictionary. For strings, this will be character or collection of characters that appears latest in the alphabet. E.g. ‘abc’ is greater than ‘abb’.
# Create a dictionary dict1 = {"b":2, "a":1, "d":4, "c":3} print("dict1 = {}".format(dict1)) # Display the maximum key value from dict1 print("max(dict1) = {}".format(max(dict1)))
Output:
dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
max(dict1) = d
min()
Returns the minimum key value from a dictionary. For strings, this will be character or collection of characters that appears earliest in the alphabet. E.g. ‘abb’ is less than ‘abc’.
# Create a dictionary dict1 = {"b":2, "a":1, "d":4, "c":3} print("dict1 = {}".format(dict1)) # Display the minimum key value from dict1 print("min(dict1) = {}".format(min(dict1)))
Output:
dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
min(dict1) = a
sorted()
Using the sorted()
function will return a sorted list of dictionary keys. The reverse
parameter can also be used to reverse the order of the list.
# Create a dictionary dict1 = {"b":2, "a":1, "d":4, "c":3} print("dict1 = {}".format(dict1)) # Return a sorted list of dictionary keys list1 = sorted(dict1) print("\nsorted(dict1) = {}".format(list1)) print("type(list1) = {}".format(type(list1)) # Return a sorted list of dictionary keys, in reverse order print("\nsorted(dict1, reverse=True) = {}".format(sorted(dict1, reverse=True))
Output:
dict1 = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
sorted(dict1) = ['a', 'b', 'c', 'd']
type(list1) =
sorted(dict1, reverse=True) = ['d', 'c', 'b', 'a']
Dictionary methods
The following methods are available for use with a Python dictionary:
Method | Description |
---|---|
clear() | Removes all items. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys() | Returns a new dictionary containing the keys defined in the 'sequence' parameter. If no 'value' parameter is provided, none will be the value assigned to each key by default. |
get() | Returns the value of a given key. Will not throw KeyError. |
items() | Returns a dynamic view object containing (key, value) tuple pairs. |
keys() | Returns a dynamic view object containing all keys. |
pop() | Removes an item based on a given key. If no key is specified, removes last item. Returns the value of the item removed. |
popitem() | Removes the last item in a dictionary. Returns a (key, value) tuple of the item removed. |
setdefault() | Returns the value of the specified key. If the key doesn't exist in the dictionary, inserts a new item with the specified (key, value) pair. |
update() | Update the dictionary with the contents of another iterable that contains (key, value) pairs. |
values() | Returns a dynamic view object containing all values. |
Clear method: .clear()
The clear()
method is used to remove all elements from the dictionary.
dict = { "key1":"value1", "key2":"value2", "key3":"value3" } dict.clear() print(dict)
Output:
{}
Copy method: .copy()
A Python dictionary can be copied using the copy()
method.
dict = { "key1":"value1", "key2":"value2", "key3":"value3" } dict_copy = dict.copy() print(dict) print(dict_copy)
Output:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Get method: .get()
The get()
method returns the value of an item in the dictionary, based on the key provided. This is slightly different to dict[“key1”], in that it won’t return a KeyError if the key doesn’t exist.
Syntax: dictionary.get(key[, default])
Both of the statements below would return None:
dict.get("invalidkey") dict.get("invalidkey", None)
Sample code for how to use the get() method:
# Create and populate our dictionary dict = { "key1":"value1", "key2":"value2", "key3":"value3" } # Dictionary contains the key, no default provided x = dict.get("key1") print(x) # Dictionary does not contain the key, default provided x = dict.get("key7", 0.0) print(x)
Output:
value1
0.0
get() Parameters:
- key: Key to search for in the dictionary.
- value (optional): Value to return if key not found in dictionary (default of None).
Items method: .items()
The items()
method returns a view object as a list of (key, value) tuples. This means if you modify the underlying list, the view object will update automatically.
Syntax: dictionary.items()
# Create a dictionary dict1 = { 'a': 1, 'b': 2, 'c': 3 } # Call .items() to assign the view object to dict2 dict2 = dict1.items() print("Result of dict1.items():\n{}".format(dict2)) print("Type: {}".format(type(dict2))) # Delete an item from the dictionary del[dict1['a']] print("\nAfter del[dict1['a']]:") print("dict1: {}".format(dict1)) print("dict2: {}".format(dict2))
Output:
Result of dict1.items():
dict_items([('a', 1), ('b', 2), ('c', 3)])
Type:
After del[dict1['a']]:
dict1: {'b': 2, 'c': 3}
dict2: dict_items([('b', 2), ('c', 3)])
Pop method: .pop()
The pop()
method removes an element from the dictionary by specifying its key.
Syntax: dictionary.pop(key[, default])
# Create a dictionary dict1 = { "key1":"value1", "key2":"value2", "key3":"value3" } print("dict1 = \n{}".format(dict1)) # Use pop() to remove the key-value pair with a key value of 'key1' dict1.pop("key1") print("\nAfter dict1.pop('key1') = \n{}".format(dict1)) # Show that pop() returns the value from the pair that was removed x = dict1.pop("key2") print("\nValue removed by dict1.pop('key2') = \n{}".format(x))
Output:
dict1 =
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
After dict1.pop('key1') =
{'key2': 'value2', 'key3': 'value3'}
Value removed by dict1.pop('key2') =
value2
It is also possible to return a default value if the key does not exist in the dictionary. If the key passed to the pop()
method is not found in the Python dictionary, and a default value is not specified, the code will raise an error.
Popitem method: .popitem()
If you want to remove the last item that was added to a dictionary, you can use popitem()
. Prior to Python 3.7, this would have removed an arbitrary item from the dictionary.
Syntax: dictionary.popitem()
# Create a dictionary dict1 = { 'a': 1, 'b': 2, 'c': 3 } print("dict1 before .popitem() = {}".format(dict1)) # Use .popitem() to remove an item from dict1 removed = dict1.popitem() print("\ndict1 after .popitem() = {}".format(dict1)) print("Removed Item = {}".format(removed)) print("Removed Item Type = {}".format(type(removed)))
Output:
dict1 before .popitem() = {'a': 1, 'b': 2, 'c': 3}
dict1 after .popitem() = {'a': 1, 'b': 2}
Removed Item = ('c', 3)
Removed Item Type =
Setdefault method: .setdefault()
The setdefault()
method will return the value associated with the given key, if the key exists in the dictionary.
If the key does not exist, setdefault
will create it. If the value
is supplied, then this will be used as the value for the item. If there is no value passed to the value
parameter, none
will be used by default.
Syntax of setdefault(): dictionary.setdefault(key[, value])
Example 1: When key is in the dictionary# Create a dictionary dict1 = {'a': 1, 'b': 2} print("dict1 = {}\n".format(dict1)) returned = dict1.setdefault('a') print("After setdefault('a'), dict1 = \n{}".format(dict1)) print("setdefault('a') returns: {}\n".format(returned))
Output:
dict1 = {'a': 1, 'b': 2}
After setdefault('a'), dict1 =
{'a': 1, 'b': 2}
setdefault('a') returns: 1
Example 2: When key is not in the dictionary
# Create a dictionary dict1 = {'a': 1, 'b': 2} print("dict1 = {}\n".format(dict1)) # Key is not in the dictionary. No default provided returned = dict1.setdefault('c') print("After setdefault('c'), dict1 = \n{}".format(dict1)) print("setdefault('c') returns: {}\n".format(returned)) # Key is not in the dictionary. Default_value provided returned = dict1.setdefault('d', 4) print("After setdefault('d'), dict1 = \n{}".format(dict1)) print("setdefault('d') returns: {}\n".format(returned))
Output:
dict1 = {'a': 1, 'b': 2}
After setdefault('c'), dict1 =
{'a': 1, 'b': 2, 'c': None}
setdefault('c') returns: None
After setdefault('d'), dict1 =
{'a': 1, 'b': 2, 'c': None, 'd': 4}
setdefault('d') returns: 4
Update method: .update()
If you have two Python dictionaries that you want to merge, you can do so using the update()
method. This merges the keys and values of multiple dictionaries, overwriting values of the same key.
Syntax: dictionary.update([other])
# Create two dictionaries dict1 = {'key1':'val1','key2':'val2'} dict2 = {'key2':'val3','key3':'val3'} # Update dict1 to also contain elements from dict2 dict1.update(dict2) # Display the elements in dict1 print(dict1)
Output:
{'key1': 'val1', 'key2': 'val3', 'key3': 'val3'}
When dict1 was merged with the keys and values of dict2. key2 had its value overwritten with a value of ‘val3’.
Dictionary Equality
The ==
and !=
operators can be used to compare the contents of two dictionaries. In the example dict1 == dict2
, if dict1
contains all the same keys and values as dict2
, then the result will be True
.
# Create two dictionaries dict1 = {"a":1, "b":2, "c":3} dict2 = {"a":1, "b":2, "c":3} print("dict1 = {}".format(dict1)) print("dict2 = {}".format(dict2)) # Check if the two dictionaries are equal print("dict1 == dict2: {}".format(dict1 == dict2)) # Check if the two dictionaries are not equal print("dict1 != dict2: {}".format(dict1 != dict2))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 2, 'c': 3}
dict1 == dict2: True
dict1 != dict2: False
Using the ‘is’ and ‘is not’ keywords
Although the elements in dict1
and dict2
are the same, they are two different objects in memory. This can be checked using the is
and is not
keywords.
# Create two dictionaries dict1 = {"a":1, "b":2, "c":3} dict2 = {"a":1, "b":2, "c":3} print("dict1 = {}".format(dict1)) print("dict2 = {}".format(dict2)) # Check whether dict2 'is' dict1 print("dict1 is dict2 = {}".format(dict1 is dict2)) # Assign dict1 to dict2, then check if dict1 is dict2 dict2 = dict1 print("\nAfter 'dict2 = dict1':") print("dict1 is dict2 = {}".format(dict1 is dict2))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 2, 'c': 3}
dict1 is dict2 = False
After 'dict2 = dict1':
dict1 is dict2 = True
So, after assigning dict1
to dict2
, we have two variables that are pointing to the same object in memory.
But what happens if we now change the contents of dict1
? Will the is
keyword still return True?
# Create two dictionaries dict1 = {"a":1, "b":2, "c":3} dict2 = {"a":1, "b":2, "c":3} print("dict1 = {}".format(dict1)) print("dict2 = {}".format(dict2)) # Check whether dict2 'is' dict1 print("dict1 is dict2 = {}".format(dict1 is dict2)) # Assign dict1 to dict2, then check if dict1 is dict2 dict2 = dict1 print("\nAfter 'dict2 = dict1':") print("dict1 is dict2 = {}".format(dict1 is dict2)) # Remove the last key-value pair from dict2 dict2.popitem() print("\nAfter 'dict2.popitem()':") print("dict1 = {}".format(dict1)) print("dict2 = {}".format(dict2)) # Check whether dict2 'is' dict1 print("dict1 is dict2 = {}".format(dict1 is dict2))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 2, 'c': 3}
dict1 is dict2 = False
After 'dict2 = dict1':
dict1 is dict2 = True
After 'dict2.popitem()':
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 1, 'b': 2}
dict1 is dict2 = True
In the code above, although we called the popitem()
method on dict2
, the last key-value pair has disappeared from both variables. That’s because they point to the same underlying object, and it’s the underlying object that had the item removed. Therefore, dict1 is dict2
still returns True.
If you did only want to change the contents of dict2
, it would need to have been created as a copy of dict1
.
# Create a dictionary dict1 = {"a":1, "b":2, "c":3} print("dict1 = {}".format(dict1)) # Create a copy of dict1 and assign to the dict2 variable dict2 = dict1.copy() # Check whether dict2 'is' dict1 print("dict1 is dict2 = {}".format(dict1 is dict2)) # Remove the last key-value pair from dict2 dict2.popitem() print("\nAfter 'dict2.popitem()':") print("dict1 = {}".format(dict1)) print("dict2 = {}".format(dict2))
Output:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict1 is dict2 = False
After 'dict2.popitem()':
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 2}
Nested Dictionaries
Although dictionary keys must be of an immutable data type, dictionary values can also be mutable. This means you can have a nested dictionary, where values of a dictionary are other dictionaries.
Syntax: nested_dict = {dict1:{key_A:value_A}, dict2:{key_B:value_B}}
Example 1: Create a nested dictionary# Create a nested dictionary nested_dict = {"dict1":{"a":1, "b":2, "c": 3}, "dict2":{"a":1, "b":2, "c": 3}} print("nested_dict = {}".format(nested_dict))
Output:
nested_dict = {'dict1': {'a': 1, 'b': 2, 'c': 3}, 'dict2': {'a': 1, 'b': 2, 'c': 3}}
Example 2: Read from a nested dictionary
# Create a nested dictionary nested_dict = {"dict1":{"a":1, "b":2, "c": 3}, "dict2":{"a":1, "b":2, "c": 3}} # Access nested dictionary values by drilling down through the keys print("nested_dict['dict1']['a'] = {}".format(nested_dict["dict1"]["a"])) print("nested_dict['dict2']['b'] = {}".format(nested_dict["dict2"]["b"]))
Output:
nested_dict['dict1']['a'] = 1
nested_dict['dict2']['b'] = 2
Example 3: Add new items to a nested dictionary
# Create a nested dictionary nested_dict = {"dict1":{"a":1, "b":2, "c": 3}, "dict2":{"a":1, "b":2, "c": 3}} # Add a new (key, value) pair to an existing nested dictionary nested_dict["dict1"]["d"] = 4 print("nested_dict['dict1'] = {}".format(nested_dict["dict1"])) # Add a new nested dictionary to the main dictionary nested_dict["dict3"] = {"d":4, "e":5, "f":6, "g":7} print("nested_dict['dict3'] = {}".format(nested_dict["dict3"])) print("nested_dict = {}".format(nested_dict))
Output:
nested_dict['dict1'] = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
nested_dict['dict3'] = {'d': 4, 'e': 5, 'f': 6, 'g': 7}
nested_dict = {'dict1': {'a': 1, 'b': 2, 'c': 3, 'd': 4}, 'dict2': {'a': 1, 'b': 2, 'c': 3},'dict3': {'d': 4, 'e': 5, 'f': 6, 'g': 7}}
Example 4: Delete from a nested dictionary
# Create a nested dictionary nested_dict = {"dict1":{"a":1, "b":2, "c": 3}, "dict2":{"a":1, "b":2, "c": 3}} print("nested_dict = {}".format(nested_dict)) # Delete an individual item from dict1 del nested_dict["dict1"]["c"] print("\nAfter del nested_dict['dict1']['c']:") print("nested_dict['dict1'] = {}".format(nested_dict["dict1"])) print("nested_dict = {}".format(nested_dict)) # Delete an entire nested dictionary from the main dictionary del nested_dict["dict2"] print("\nAfter del nested_dict['dict2']:") print("nested_dict = {}".format(nested_dict))
Output:
nested_dict = {'dict1': {'a': 1, 'b': 2, 'c': 3}, 'dict2': {'a': 1, 'b': 2, 'c': 3}}
After del nested_dict['dict1']['c']:
nested_dict['dict1'] = {'a': 1, 'b': 2}
nested_dict = {'dict1': {'a': 1, 'b': 2}, 'dict2': {'a': 1, 'b': 2, 'c': 3}}
After del nested_dict['dict2']:
nested_dict = {'dict1': {'a': 1, 'b': 2}}