🎏 This is the 15th day of my participation in the Gwen Challenge. Check out the details: Gwen Challenge

0 x00 📢 preface

Python is a programming language that knows how not to interfere with your programming. It’s easy to learn and powerful enough to build Web applications and automate boring stuff.

This article introduces the Dictionary of sequence types.

0 x01 Dictionary (Dictionary)

A Dictionary is a built-in type for sequences and is one of the most commonly used Python data types. It is an unordered, mutable sequence whose elements are stored as key-value pairs and can store objects of any type.

Dictionaries are also called associative arrays or hash tables. It retrieves the specified item from the dictionary by key, but not by index, so the key in the dictionary must be unique.

Create a dictionary

The dictionary consists of pairs of keys and values. Each pair of keys and values is separated by commas. The whole dictionary is enclosed in curly braces {}.

dict1 = {key1 : value1, key2 : value2, ... }
Copy the code

Create using curly brace syntax.

>>> dict1 = { 'name' : 'apple' , 'price' : 800 } 
>>> dict1
{'name': 'apple'.'price': 800}
 

# empty dictionary
>>> dict1 = {}
>>> dict1
{}
Copy the code

Create using fromKeys ()

Use the fromKeys () method provided by the dictionary type to create a dictionary with default values, using the elements in the list sequence as the dictionary keys, and value as the initial values for all the keys in the dictionary.

dictname = dict.fromkeys(list, value =None)
Copy the code

The following is an example.

>>> fruits_list = ['apple'.'banana'.'grape'] 
>>> fruits_dict = dict.fromkeys( fruits_list, 600 )         
>>> fruits_dict                                      
{'apple': 600.'banana': 600.'grape': 600}
Copy the code

Created using the constructor dict()

Use the dict() constructor to create a new dictionary

>>> banana_dict = dict(name="banana", price=200) 
>>> banana_dict
{'name': 'banana'.'price': 200}

Create an empty dictionary
>>> empty_dict = dict(a)>>> empty_dict
{}
Copy the code

The dict() constructor supports more complex parameter creation dictionaries.

dict(a=1, b=2, c=3)                   
dict([('a'.1), ('b'.2), ('c'.3)])  
dict([('a'.1)], b=2, c=3)            
dict({'a' : 1.'b' : 2}, c=3)   
Creating a dictionary is the same
{'a': 1.'b': 2.'c': 3}
Copy the code

Type () Indicates the type

View the data type through the type() function.

>>> type({'a': 1.'b': 2.'c': 3})"class 'dict'>
Copy the code

Access to a dictionary

Lists and tuples access elements through subscripts, while dictionaries access values through keys. Because the elements in a dictionary are unordered and each element is not in a fixed position, you cannot use indexes or slices to access elements like lists and tuples.

>>> dict1 = { 'name' : 'apple' , 'price' : 800 } 
>>> dict1['name'] 
'apple' 
Copy the code

An error is reported if the accessed key does not exist.

>>> dict1['weight']
Traceback (most recent call last):   
  File "<stdin>", line 1.in <module>
KeyError: 'weight'
Copy the code

Use the get() method

The dictionary type provides the get() method to get the value of the specified key. The get() method does not throw an exception when the specified key does not exist.

Get () uses the following: dict_name denotes the name of the dictionary variable; Key indicates the specified key. Default specifies the default value returned by this method if the key to be queried does not exist, or None if you do not specify it manually.

dict_name.get(key, default=None)
Copy the code

The following is an example.

>>> dict1 = {'a': 1.'b': 2.'c': 3} 
>>> dict1.get('a') 
1

There is no key in access
>>> print( dict1.get('d'))None
>>> dict1.get('d'.'key not found! ')
'key not found! ' 
Copy the code

Membership check

To determine whether a dictionary contains keys for a specified key-value pair, you can use the IN or not in operators based on keys.

>>> dict1 = {'a': 1.'b': 2.'c': 3} 
>>> 'a' in dict1
True
>>> 'c' not  in dict1 
False
Copy the code

Iteration

Use the for loop to iterate over any iterable dictionary.

>>> dict1 = {'a': 1.'b': 2.'c': 3}
>>> for key in dict1:
.    print(key)
...
a
c
b
Copy the code

Use built-in methods to iterate over key values.

d = {'a': 1.'b': 2.'c': 3}
Iteration # key
>>> for k in d.keys():
.  print(k) 
.
a
b
c
 
# iteration value
>>> for v in d.values():
.  print(v)
.
1
2
3
  
# Iterating over key-value pairs
>>> for k, v in d.items():
.  print('{}, {}'.format(k, v))
.
a:1
b:2
c:3
Copy the code

To modify a dictionary

Add key-value pairs

Adding a new key-value pair to a dictionary is as simple as assigning a value to a key that doesn’t exist.

>>> d = {'a': 1.'b': 2.'c': 3}
>>> d['c'] = 4
>>> d
{'a': 1.'b': 2.'c': 4}
Copy the code

Modify key/value pairs

Keys in dictionaries cannot be modified and must be unique. Only values can be modified. Update the element value by accessing an existing key value and then performing an assignment.

>>> d = {'a': 1.'b': 2.'c': 3}
>>> d['a'] = 0 
>>> d
{'a': 0.'b': 2.'c': 3}
Copy the code

To delete a dictionary

Use the DEL statement to delete a dictionary element or dictionary.

>>> dict1 = {'a': 1.'b': 2.'c': 3}   
>>> del dict1['a'] 
>>> dict1
{'b': 2.'c': 3}

>>> del dict1     
>>> dict1     
Traceback (most recent call last):    
  File "<stdin>", line 1.in <module> 
NameError: name 'dict1' is not defined  
Copy the code

Use the clear() method

The dictionary type provides the use of the clear() method to delete all elements in the dictionary.

>>> dict1 = {'a': 1.'b': 2.'c': 3}   
>>> dict1.clear()
>>> dict1
{}  
Copy the code

String formatting

In the previous string formatting, if the string template contains a large number of variables, you need to give multiple variables in order. Python provides a more user-friendly way to format and output strings using dictionaries.

>>> string_tmp = '%(name)s %(price)008.2f' 
>>> dict1 = { 'name' : 'apple' , 'price' : 800 } 
>>> string_tmp % dict1
'Name is: Apple, price is :00800.00'
Copy the code