Dictionary type (dictionary) saves data in key-value store.
If you don't know about key-value stores, think of a zip code.
A zip code is a system that stores data with typical key values.
Key: 107-0052 Value: Akasaka, Minato-ku, Tokyo
Key: 160-0021 Value: Kabukicho, Shinjuku-ku, Tokyo
Another key value is the relationship between the student ID number and the student name.
Dictionary in Python
d = {'key1' : 'Value1', 'key2' : 'Value2'}
It is defined as.
Copy the following program and execute it. I will explain each function.
dictionary_explain.py
d = {'key1' : 'Value1', 'key2' : 'Value2'}
print("len(d) {0}".format(len(d)))
print("min(d) {0}".format(min(d)))
print("max(d) {0}".format(max(d)))
dic_d_key1 = 'key1' in d
dic_d_key3 = 'key3' in d
print("dic_d_key1 {0}".format(dic_d_key1))
print("dic_d_key3 {0}".format(dic_d_key3))
print("d[key1 {0}".format(d['key1']))
print("d[key1 {0}".format(d.get('key1')))
print("d[key1 {0}".format(d.get('key3')))
print("d[key1 {0}".format(d.get('key3','No Existance')))
d['key1'] = 'NewValue1'
d['key3'] = 'Value3'
del d['key2']
print("d {0}".format(d))
print(d.pop('key3'))
print("d {0}".format(d))
You can check if an element exists in the dictionary with ** Key in Dictionary **.
You can get the number of data in the dictionary by writing ** len (dictionary) **. ** max (dictionary) ** and ** min (dictionary) ** return the key ** of the ** data with the largest / smallest data in the dictionary.
If you want to get the value in the dictionary, specify the key. It can be obtained by ** dictionary [key] **, but in this notation, it does not exist in the dictionary. If you specify a key, an error will occur. There is also a way to check that the key exists with ** Key in Dictionary ** and process it, Another way to specify the key is ** Dictionary.get (key) **. This does not exist in the dictionary Specifying the key does not cause an error. further, By writing ** dictionary.get (key, value when key does not exist) ** You can set the value to be returned when the key does not exist.
** Dictionary [key] = Value ** If the key does not exist in the dictionary, data will be added, and if it exists, the value will be updated.
** del Dictionary [key] ** Delete the key and the value data corresponding to the key. However, it does not exist in the dictionary If you specify a key, an error will occur. ** Dictionary.pop (key) ** is deleted after getting the value, as you can see in the output result of the program. (Imagine the process of removing from the box) However, if you specify a key that does not exist in the dictionary, an error will occur. There is also a way to check that the key exists with ** Key in Dictionary ** and process it, Like get, pop can be described as ** dictionary.pop (key, value when key does not exist) **. It can be written to return the value if the key does not exist without causing an error.
Next: Python Basic Course (8 branches)
Recommended Posts