YouTip LogoYouTip

Python Dictionary

# Python2.x Python 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 `:`, each key-value pair is separated by a comma `,`, and the entire dictionary is enclosed in curly braces `{}`, as shown in the following format: d = {key1 : value1, key2 : value2 } **Note:** `dict` is a keyword and built-in function in Python, so it is not recommended to name a variable **dict**. Keys are generally unique. If there are duplicates, the last key-value pair will replace the previous ones. Values do not need to be unique. >>> tinydict ={'a': 1,'b': 2,'b': '3'} >>> tinydict['b'] '3' >>> tinydict {'a': 1,'b': '3'} Values can be of any data type, but keys must be immutable, such as strings, numbers, or tuples. A simple dictionary example: tinydict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} A dictionary can also be created like this: tinydict1 = { 'abc': 456 } tinydict2 = { 'abc': 123, 98.6: 37 } * * * ## Accessing Values in a Dictionary Place the corresponding key in familiar square brackets, as shown in the following example: ## Example #!/usr/bin/python tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print"tinydict['Name']: ", tinydict['Name']print"tinydict['Age']: ", tinydict['Age'] The output of the above example is: tinydict['Name']: Zara tinydict['Age']: 7 If you access data using a key that does not exist in the dictionary, an error will be output as follows: ## Example #!/usr/bin/python tinydict = {'Name': 'Tutorial', 'Age': 7, 'Class': 'First'} print"tinydict['Alice']: ", tinydict['Alice'] The output of the above example is: tinydict['Alice']: Traceback (most recent call last): File "test.py", line 5, in print "tinydict['Alice']: ", tinydict['Alice']KeyError: 'Alice' * * * ## Modifying a Dictionary The way to add new content to a dictionary is to add new key/value pairs, or modify or delete existing key/value pairs, as shown in the following example: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} tinydict['Age'] = 8# Update tinydict['School'] = "TUTORIAL"# Add print"tinydict['Age']: ", tinydict['Age']print"tinydict['School']: ", tinydict['School'] The output of the above example is: tinydict['Age']: 8 tinydict['School']: TUTORIAL * * * ## Deleting Dictionary Elements You can delete a single element or clear the entire dictionary. Clearing requires only one operation. To explicitly delete a dictionary, use the `del` command, as shown in the following example: ## Example #!/usr/bin/python# -*- coding: UTF-8 -*-tinydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del tinydict['Name']# Delete the entry with key 'Name' tinydict.clear()# Clear all entries in the dictionary del tinydict# Delete the dictionary print"tinydict['Age']: ", tinydict['Age']print"tinydict['School']: ", tinydict['School'] However, this will raise an exception because the dictionary no longer exists after using `del`: tinydict['Age']: Traceback (most recent call last): File "test.py", line 10, in print "tinydict['Age']: ", tinydict['Age'] NameError: name 'tinydict' is not defined **Note:** The `del()` method will also be discussed later. ### Characteristics of Dictionary Keys Dictionary values can be any Python object without restriction, including both standard objects and user-defined objects. However, keys cannot. Two important points to remember: 1) The same key cannot appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as shown in the following example: ## Example #!/usr/bin/python tinydict = {'Name': 'Tutorial', 'Age': 7, 'Name': 'Manni'} print"tinydict['Name']: ", tinydict['Name'] The output of the above example is: tinydict['Name']: Manni 2) Keys must be immutable, so numbers, strings, or tuples can be used as keys. Lists cannot be used, as shown in the following example: ## Example #!/usr/bin/python tinydict = {['Name']: 'Zara', 'Age': 7} print"tinydict['Name']: ", tinydict['Name'] The output of the above example is: Traceback (most recent call last): File "test.py", line 3, in tinydict = {['Name']: 'Zara', 'Age': 7} TypeError: unhashable type: 'list' * * * ## Built-in Dictionary Functions & Methods Python dictionaries include the following built-in functions: | No. | Function and Description | | --- | --- | | 1 | [cmp(dict1, dict2)](#) Compares two dictionary elements. | | 2 | [len(dict)](#) Calculates the number of elements in the dictionary, i.e., the total number of keys. | | 3 | [str(dict)](#) Outputs a printable string representation of the dictionary. | | 4 | [type(variable)](#) Returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type. | Python dictionaries include the following built-in methods: | No. | Function and Description | | --- | --- | | 1 | [dict.clear()](#) Deletes all elements in the dictionary. | | 2 | [dict.copy()](#) Returns a shallow copy of the dictionary. | | 3 | [dict.fromkeys(seq[, val])](#) Creates a new dictionary with elements from sequence `seq` as keys and `val` as the initial value for all keys. | | 4 | [dict.get(key, default=None)](#) Returns the value for the specified key. If the key is not in the dictionary, returns `default`. | | 5 | [dict.has_key(key)](#) Returns `true` if the key is in the dictionary, otherwise returns `false`. Not supported in Python3. | | 6 | [dict.items()](#) Returns a list of the dictionary's (key, value) tuple pairs. | | 7 | [dict.keys()](#) Returns a list of all keys in the dictionary. | | 8 | [dict.setdefault(key, default=None)](#) Similar to `get()`, but if the key is not in the dictionary, it will add the key and set the value to `default`. | | 9 | [dict.update(dict2)](#) Updates the dictionary with key/value pairs from `dict2`. | | 10 | [dict.values()](#) Returns a list of all values in the dictionary. | | 11 | [pop(key[,default])](#) Deletes the value corresponding to the given key `key` and returns the deleted value. The key must be provided. Otherwise, returns the `default` value. | | 12 | [popitem()](#) Returns and deletes the last key-value pair from the dictionary. |
← Ios SetupFunc Number Atan β†’