Latest web development tutorials

Python3 dictionary

Another variable is the dictionary container model, and can store any type of object.

Each dictionary key (key => value) of the colon(:) divided between each pair with a comma (,)division, including the entire dictionary in curly braces({}),the format is as follows:

d = {key1 : value1, key2 : value2 }

Key must be unique, but the value is not necessary.

Value can take any data type, but the key must be immutable, such as strings, numbers, or tuples.

A simple dictionary Example:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

So also create the dictionary:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Access the dictionary values

The corresponding key in the familiar square brackets following examples:

#!/usr/bin/python3

dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}

print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

Examples of the above output:

dict['Name']:  w3big
dict['Age']:  7

If there is no key to access the data dictionary, it will output the following error:

#!/usr/bin/python3
 
dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'};
 
print ("dict['Alice']: ", dict['Alice'])

Examples of the above output:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'


Modifying a dictionary

Way to add new content to the dictionary to add new key / value pairs, modify or delete existing key / value pairs following examples:

#!/usr/bin/python3

dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8;               # 更新 Age
dict['School'] = "本教程"  # 添加信息


print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Examples of the above output:
dict['Age']:  8
dict['School']:  本教程


Delete dictionary elements

Can delete a single element can be empty dictionary, emptied just one operation.

To delete a dictionary with the del command, the following examples:

#!/usr/bin/python3

dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}

del dict['Name'] # 删除键 'Name'
dict.clear()     # 删除字典
del dict         # 删除字典

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

But this raises an exception, because with the operation after performing del dictionaries no longer exists:

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 next del () method will be discussed.


Characteristics of the dictionary key

Dictionary values ​​can be taken without limitation, any python object can be both standard object, it can be user-defined, but the key does not work.

Two important points to remember:

1) does not allow the same key appears twice. When you create is assigned if the same key twice, the latter value will be remembered, the following examples:

#!/usr/bin/python3

dict = {'Name': 'w3big', 'Age': 7, 'Name': '小本'}

print ("dict['Name']: ", dict['Name'])

Examples of the above output:

dict['Name']:  小本

2) key must not be changed, so you can use numeric, string, or tuple to act as, and will not work with the list, the following examples:

#!/usr/bin/python3

dict = {['Name']: 'w3big', 'Age': 7}

print ("dict['Name']: ", dict['Name'])

Examples of the above output:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'w3big', 'Age': 7}
TypeError: unhashable type: 'list'


Dictionary built-in functions & methods

Python dictionary contains the following built-in functions:

No. Function and description Examples
1 len (dict)
Counting the number of dictionary elements, namely the total number of keys.
>>> dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
2 str (dict)
Output dictionaries printable string representation.
>>> dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'w3big', 'Class': 'First', 'Age': 7}"
3 type (variable)
Returns the type of input variable, if the variable is a dictionary returns a dictionary.
>>> dict = {'Name': 'w3big', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>

Python dictionary contains the following built-in method:

No. Function and description
1 radiansdict.clear ()
Delete all the elements in the dictionary
2 radiansdict.copy ()
Returns a shallow copy of dictionary
3 radiansdict.fromkeys ()
Create a new dictionary to the sequence seq elements do dictionary key, val as a dictionary of all the key corresponding to the initial value
4 radiansdict.get (key, default = None)
Returns the value of the specified key, if the return value is not in the dictionary default values
5 key in dict
Returns true if the key is in the dictionary dict, otherwise returns false
6 radiansdict.items ()
Returns a list traversal (key, value) tuples array
7 radiansdict.keys ()
To return a list of all the keys dictionary
8 radiansdict.setdefault (key, default = None)
And get () is similar, but if the key does not exist in the dictionary, and will add value to default keys
9 radiansdict.update (dict2)
Dict2 the dictionary of key / value pairs in the update to the dict
10 radiansdict.values ()
To return a list of all the values ​​in the dictionary