Let's dive into the world of dictionaries, a fundamental data structure in Python. We'll cover how to create, access, and manipulate key-value pairs within dictionaries.
A dictionary in Python is an unordered collection of key-value pairs. It's a data structure that allows you to store and retrieve data using unique keys. Each key is associated with a corresponding value.
We'll learn about the following topics:
Name | Type in Python | Description | Example |
---|---|---|---|
Dictionaries | dict | Unordered key:value pairs in { }. | {'key':10, 'word': 'hello'} |
Dictionaries are a type of mapping. Mappings are collections of objects stored with unique keys, unlike sequences that store objects based on their relative positions. This distinction is significant because mappings do not preserve the order of objects, as they are defined by their keys.
type({'key':10, 'word': 'hello'})
dict
Dictionaries in Python are created using curly braces {}
. Each key-value pair within the dictionary is separated by a colon :
.
b = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
It's important to note that dictionaries are very flexible in the data types they can hold.
a = {'key1':123, 'key2':[12,23,33], 'key3':['item0','item1','item2']}
Please note that keys in a Python dictionary can be any immutable object, including numbers, strings, tuples, and booleans. Lists cannot be used as keys because they are mutable.
my_dict = {1: "apple", (1, 2): "point A", True: "enabled"}
len()
: Python's built-in len() function returns the number of key-value pairs in the dictionary.len(a)
3
To access the value associated with a specific key in a dictionary, you use square brackets []
and provide the key as an argument.
Name_of_Dictionary[key]
---> value
a
{'key1': 123, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2']}
a['key3']
['item0', 'item1', 'item2']
#Can call an index on that value
a['key2'][0]
12
a['key2'][-1]
33
a = {'key1':123, 'key2':[12,23,33], 'key3':['item0','item1','item2']}
b = {'key2':[12,23,33], 'key3':['item0','item1','item2'], 'key1':123}
a == b
True
This clearly shows that dictionaries are not ordered.
a['key1'] = 125
a
{'key1': 125, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2']}
#Can then even call methods on that value
a['key3'][0].upper()
'ITEM0'
We can affect the values of a key as well. For instance:
#Subtract from the value
a['key1'] = a['key1'] - 12
a
{'key1': 113, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2']}
Just a quick note: In Python, there's a convenient built-in method for performing self-subtraction, addition, multiplication, or division. Alternatively, we could use the += -= *= /= etc. operators. For example:
a['key1'] /= 2
a
{'key1': 56.5, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2']}
in
: Python also provides a membership operator that can be used with dictionaries. The in operator returns True if a key exists in the dictionary, and False otherwise.'key1' in a
True
not in
: Python also provides a membership operator that can be used with dictionaries. The not in operator returns True if a key doesn't exist in the dictionary, and False otherwise.'key1' not in a
False
Method | Description |
---|---|
keys() | return a list of all keys |
values() | return a list of all values |
items() | return tuples of all items |
update(2nd dic) | Merge two dictionaries |
get(key) | returns the value for a given key |
pop(key) | removes the specified ke0value pair from the dictionary and return the value of the removed key |
popitem() | removes and returns an arbitrary key-value pair from the dictionary as a tuple |
clear() | empties dictionary of all key-value pairs |
a.keys()
dict_keys(['key1', 'key2', 'key3'])
a.values()
dict_values([56.5, [12, 23, 33], ['item0', 'item1', 'item2']])
a.items()
dict_items([('key1', 56.5), ('key2', [12, 23, 33]), ('key3', ['item0', 'item1', 'item2'])])
b = {'one':1, 'two':2}
c = {'three': 3, 'four': 4}
b.update(c)
b
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
Instead of using .update()
method, you can add a new key-value pair in the following way:
a['programming'] = 'Python'
print(a)
{'key1': 56.5, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2'], 'programming': 'Python'}
We can't directly concatenate dictionaries using the +
operator.
a.get('key1')
56.5
.get()
is equivalent to dictionary_name[key_name]
.
a['key1']
56.5
a.pop('programming')
'Python'
a
{'key1': 56.5, 'key2': [12, 23, 33], 'key3': ['item0', 'item1', 'item2']}
key_pop, value_pop = a.popitem()
print('Removed Key:', key_pop)
print('Removed Value:', value_pop)
print('Updated Dictionary:', a)
Removed Key: key3 Removed Value: ['item0', 'item1', 'item2'] Updated Dictionary: {'key1': 56.5, 'key2': [12, 23, 33]}
a.clear()
a
{}
dic1 = {'key1':{'nestkey':{'subnestkey':'value'}}}
#Keep calling the keys
dic1['key1']['nestkey']['subnestkey']
'value'
Dictionaries and lists share the following characteristics:
Dictionaries differ from lists primarily in how elements are accessed: