A dictionary in Python is a collection of key:value pair s.Similar to Map or lookup table s in other languages.
The key must be a string, and the value can be any object.
Both key and value can use variables.
Simple Dictionary
student = {'name': 'tony', 'age': 14} print(student ['name']) print(student ['age'])
Using a dictionary
Dictionaries are contained between {and}, members (key-value pairs), and delimited.The member's value is accessible through the key.
An empty dictionary is defined as follows:
student = {}
Adding members to a dictionary directly assigns a value, which is equivalent to updating if the key already exists:
>>> student = {'name': 'tony', 'age': 14} >>> student['grade']=7 >>> print(student) {'grade': 7, 'age': 14, 'name': 'tony'} >>> student['age']=15 >>> print(student) {'grade': 7, 'age': 15, 'name': 'tony'} >>> student['age'] += 1 >>> print(student) {'grade': 7, 'age': 16, 'name': 'tony'}
Delete members using del, as in List:
>>> del student['age'] >>> print(student) {'grade': 7, 'name': 'tony'}
A beautiful way of writing:
>>> student = { ... 'name':'tony', ... 'age':14 ... }
If the key does not exist, there will be an error accessing its value:
>>> student['gender'] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'gender'
This requires the get() method, the first parameter is the key, and the second parameter is optional, which is returned when the key is not assigned:
>>> student.get('gender', 'No value assigned') 'No value assigned'
If the key is not assigned and the get method does not specify the second parameter, it returns None, which is equivalent to Null in SQL:
>>> ret = student.get('gender') >>> ret >>> print(ret) None
Of course, None can also be used directly as value:
>>> a={'a':None,'b':None} >>> print(a.get('a')) None
Traverse Dictionary
Take the following form:
for k, v in dictionary.items()
Example:
$ cat months.py months = {'jan':1, 'feb':2, 'march':3, 'apr':4} for k,v in months.items(): print(f"key is {k.upper()}, value is {v}") print() for k in months.keys(): print(f"key is {k.upper()}") print() for v in months.values(): print(f"value is {v}") $ python3 months.py key is JAN, value is 1 key is FEB, value is 2 key is MARCH, value is 3 key is APR, value is 4 key is JAN key is FEB key is MARCH key is APR value is 1 value is 2 value is 3 value is 4
If you want to access key s in a dictionary in a certain order, you can use the sorted function:
for k in sorted(dictionary.keys()): ...
The key in the dictionary is of course unique, but the value may be sufficient and we can remove duplicate values through the set function:
>>> ages = {'tony':14, 'tom':14, 'ivan':15} >>> ages.values() dict_values([14, 14, 15]) >>> set(ages.values()) {14, 15}
set can be thought of as a List with unique values, which is defined much like a dictionary, using {and} when the member is not key:value, but a single value.
>>> colors = {'red', 'blue', 'yellow', 'red'} >>> colors {'yellow', 'blue', 'red'}
nesting
First, nesting means that a dictionary can be a member of a List.
$ cat students.py students = [] for i in range(4): students.append({'no':i, 'name':'student' + f"{i}"}) print(students) print() for student in students[1:3]: print(student) $ python3 students.py [{'no': 0, 'name': 'student0'}, {'no': 1, 'name': 'student1'}, {'no': 2, 'name': 'student2'}, {'no': 3, 'name': 'student3'}] {'no': 1, 'name': 'student1'} {'no': 2, 'name': 'student2'}
Secondly, nested means that members of a dictionary can be List s.
>>> student = {'name':'tony', 'friends':['flora', 'amy']}
Finally, nesting can mean that a dictionary can contain a dictionary, that is, a dictionary can be used as a value in a dictionary member.
>>> student = {'first':'vivian', 'last':'liu', 'age':14} >>> students = {'vivian_liu':student} >>> print(students) {'vivian_liu': {'first': 'vivian', 'last': 'liu', 'age': 14}}