Python 3 Dictionary
Python 3 Dictionary
A dictionary is another mutable container model that can store objects of any type.
Each key=>value pair in a dictionary is separated by a colon (:), and each pair is separated by a comma (,). The entire dictionary is enclosed in curly braces ({}) and has the following format:
d = {key1 : value1, key2 : value2 }
Keys must be unique, but values do not need to be.
Values can be of any data type, but keys must be immutable, such as strings, numbers, or tuples.
A simple dictionary example:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary like this:
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
Accessing dictionary values
Place the corresponding key in square brackets, as shown below:
Example
#!/usr/bin/python3
dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
The above example outputs:
dict['Name']: Geekdoc
dict['Age']: 7
If you access data using a key that is not in the dictionary, you will get an error like the following:
Example
#!/usr/bin/python3
dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'}
print ("dict['Alice']: ", dict['Alice'])
The above example outputs:
Traceback (most recent call last):
File "test.py", line 5, in <module>
print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'
Modifying a Dictionary
Adding new content to a dictionary involves adding new key/value pairs and modifying or deleting existing key/value pairs. The following example shows:
Example
#!/usr/bin/python3
dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # Update Age
dict['School'] = "Geek Tutorial" # Add information
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
The above example outputs:
dict['Age']: 8
dict['School']: Geek Tutorial
Deleting Dictionary Elements
You can delete a single element or clear a dictionary; clearing a dictionary only requires one operation.
Use the del command to explicitly delete a dictionary, as shown in the following example:
Example
#!/usr/bin/python3
dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'}
del dict['Name'] # Delete the key 'Name'
dict.clear() # Clear the dictionary
del dict # Delete the dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
However, this will raise an exception because the dictionary no longer exists after the del operation:
Traceback (most recent call last):
File "test.py", line 9, in <module>
print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable
Note: The del() method will be discussed later.
Characteristics of Dictionary Keys
Dictionary values can be any python object, both standard and user-defined, but keys cannot.
Two important points to remember:
1) The same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered, as shown in the following example:
Example:
#!/usr/bin/python3
dict = {‘Name’: ‘Geekdoc’, ‘Age’: 7, ‘Name’: ‘小治客’}
print (“dict[‘Name’]: “, dict[‘Name’])
Output of the above example:
dict['Name']: 小治客
<p>2) Keys must be immutable, so numbers, strings, or tuples can be used, but lists cannot.
Example:
<pre><code class="language-python line-numbers">Example:
#!/usr/bin/python3
dict = {['Name']: 'Geekdoc', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
The above example outputs:
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Geekdoc', 'Age': 7}
TypeError: unhashable type: 'list'
Dictionary Built-in Functions & Methods
Python dictionaries include the following built-in functions:
Sequence Number | Function and Description | Example |
---|---|---|
1 | len(dict) Counts the number of dictionary elements, i.e., the total number of keys. |
>>> dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'} >>> len(dict) 3 |
2 | str(dict) Outputs the dictionary as a printable string. |
>>> dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'} >>> str(dict) "{'Name': 'Geekdoc', 'Class': 'First', 'Age': 7}" |
3 | type(variable) Returns the input variable type. If the variable is a dictionary, it returns the dictionary type. |
>>> dict = {'Name': 'Geekdoc', 'Age': 7, 'Class': 'First'} >>> type(dict) |
Python dictionaries have the following built-in methods:
Order Number | Function and Description |
---|---|
1 | radiansdict.clear() Delete all elements in a dictionary |
2 | radiansdict.copy() Returns a shallow copy of a dictionary |
3 | radiansdict.fromkeys() Creates a new dictionary with the elements in the sequence seq as the dictionary keys and val as the initial values for all keys in the dictionary |
4 | radiansdict.get(key, default=None) Returns the value of the specified key. If the value is not in the dictionary, returns the default value |
5 | key in dict Returns true if the key is in the dictionary dict, false otherwise |
6 | radiansdict.items() Returns an iterable array of (key, value) tuples as a list |
7 | radiansdict.keys() Returns an iterator that can be converted to a list using list() |
8 | radiansdict.setdefault(key, default=None)
Similar to get(), However, if the key does not exist in the dictionary, it will be added and the value will be set to default. |
9 | radiansdict.update(dict2) Updates the key/value pairs in dict2 to dict. |
10 | radiansdict.values() Returns an iterator that can be converted to a list using list(). |
11 | pop(key[,default]) Deletes the value corresponding to the given key from the dictionary, returning the deleted value. The key value must be given. Otherwise, returns the default value. |
12 | popitem() Returns and deletes the last key and value pair in the dictionary. |
x = True
country_counter = {}
def addone(country):
if country in country_counter:
country_counter[country] += 1
else:
country_counter[country] = 1
addone('China')
addone('Japan')
addone('china')
print(len(country_counter))
confusion = {}
confusion[1] = 1
confusion['1'] = 2
confusion[1] += 1
sum = 0
for k in confusion:
sum += confusion[k]
print(sum)
After-class exercises