Dict of Python's built-in data type

Dict dictionary, another mutable type container model, can store objects of any type.

1, the creation of the dictionary

Each key-value pair (key->value) of the dictionary is separated by a colon (:), the key-value pair is separated by a comma (,), and the elements are enclosed by curly braces {}. Keys must be unique, values ​​can be non-unique.

Values ​​can take any data type, but keys must be immutable, such as numbers, strings, tuples. The following is an example of a dictionary:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create an empty dictionary:

dict={}
2. Dictionary access

You can simply use the form d[key] to find the corresponding value, which is similar to list, except that list must use the index to return the corresponding element, while dict uses the key:

print dict['Beth']
result:

9102

If the key in the square brackets exists, the corresponding value will be returned. If it does not exist, an error will be reported: KeyError.

There are two ways to avoid KeyError:

(1) Before using the key to access the dictionary, first determine whether the key exists:

if 'Beth' in dict:
    print dict['Beth']
(2) Use the get method provided by Dict itself, and return None when the key does not exist:

print dict.get('Tom') #None
3. Modify the dictionary

The methods of modifying the dictionary include adding new key-value pairs, modifying the value of existing keys and deleting existing key-value pairs:

(1) Add a new key-value pair:

dict['Tom']='1234' #add new entry
dict['Alice']='0000' #update existing entry
print dict
result:

{'Alice': '0000', 'Beth': '9102', 'Cecil': '3258','Tom':'1234'}

4. Delete dictionary elements

You can delete dictionary elements, empty the dictionary, and delete the entire dictionary:

del dict['Tom'] #delete an entry
dict.clear() #Empty the dictionary, but the dict still exists, it is an empty dictionary
del dict #Display delete dictionary, dict does not exist, and there will be an error when accessing again
5, the characteristics of the dictionary

(1) The first feature of dict is that the search speed is fast. Whether the dict has 10 elements or 100,000 elements, the search speed is the same. The search speed of the list gradually decreases as the number of elements increases.

However, the fast search speed of dict is not without cost. The disadvantage of dict is that it occupies a large amount of memory and wastes a lot of content. List is just the opposite, occupying less memory, but the search speed is slow.

Since the dictionary looks up elements by key, the keys in the dictionary cannot be repeated.

(2) The second feature of dict is that the stored key-value pairs are in no order! This is not the same as list. That is, dictionaries are unordered and cannot be used to store ordered collections.

(3) The third feature of dict is that the elements used as keys must be immutable. The basic types of Python such as strings, integers, floating-point numbers and tuples are immutable and can be used as keys. But the list is mutable and cannot be used as a key. But value is mutable.

6. Traversal of the dictionary

A dict is also a collection, so its traversal is similar to that of a list. A for loop can be traversed:

dict = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }
for key in dict:
    print key+":"+str(dict[key])
result:

Lisa:85
Adam:95
Bart:59
7. Iteration of the dictionary

The dictionary type has several built-in functions that can be used to iterate over dictionary elements: keys(), values(), items():

keys returns a list of all keys of the dictionary, values ​​returns a list of all values, and item returns a list of key-value pairs:


Now you can iterate over the dictionary like this:

for key,value in dict:
    print key,":",value
result:

Lisa:85
Adam:95
Bart:59
8. Python built-in functions


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364385&siteId=291194637