Python in the dictionary (dictionary) is a set of key-value pairs: a set of (key value pair) is. Similar to other languages Map or lookup table.
key must be a string, value can be any object.
key and value variables can be used.
Simple dictionary
student = {'name': 'tony', 'age': 14}
print(student ['name'])
print(student ['age'])
Use a dictionary
Included in the dictionary {
and }
between members (key-value pairs) used between ,
separated. Members can access the value (value) by the key (key).
Empty dictionary is defined as follows:
student = {}
To increase the membership of the direct assignment to the dictionary, if it exists equivalent key updates:
>>> 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'}
Remove members using del, and this List as:
>>> del student['age']
>>> print(student)
{'grade': 7, 'name': 'tony'}
In a nice wording:
>>> student = {
... 'name':'tony',
... 'age':14
... }
If the key is not present, the value of which will be given access to:
>>> student['gender']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'gender'
It is required to use get () method, a first key parameter, the second parameter is optional, when the key is not assigned, the return value:
>>> student.get('gender', 'No value assigned')
'No value assigned'
If the key is not assigned, and the method does not get a second argument specifies, returns None, SQL equivalent of Null:
>>> ret = student.get('gender')
>>> ret
>>> print(ret)
None
Of course, None can be used directly as a value:
>>> a={'a':None,'b':None}
>>> print(a.get('a'))
None
Traversal Dictionary
It takes the 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 the dictionary key in a certain order, use the sorted function:
for k in sorted(dictionary.keys()):
...
Dictionary key of course is unique, but it is possible to fully value, we can remove duplicate values set by function:
>>> ages = {'tony':14, 'tom':14, 'ivan':15}
>>> ages.values()
dict_values([14, 14, 15])
>>> set(ages.values())
{14, 15}
List set can be considered a unique value, which is defined with the dictionary is very similar, also with {
and }
, when members are not key: value, but the value of the individual.
>>> colors = {'red', 'blue', 'yellow', 'red'}
>>> colors
{'yellow', 'blue', 'red'}
Nesting
First, nesting refers to the dictionary can be used as a member of the 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, nesting refers to a member of the dictionary can be a List.
>>> student = {'name':'tony', 'friends':['flora', 'amy']}
Finally, the nest can also refer to the dictionary may include dictionaries, dictionaries as dictionary is a member of value.
>>> student = {'first':'vivian', 'last':'liu', 'age':14}
>>> students = {'vivian_liu':student}
>>> print(students)
{'vivian_liu': {'first': 'vivian', 'last': 'liu', 'age': 14}}