官术网_书友最值得收藏!

Dictionaries

The first data structure we're going to look at is Python's dictionary. A dictionary consists of any number of key-value pairs. The key can be used to get or set the value or remove the pair from the dictionary entirely.

Similar data structures in other languages are sometimes called maps or hash tables.

There are several ways to create a dictionary in Python. The simplest is to use a dictionary expression, which is just a pair of curly brackets surrounding the key-value pairs we want in the dictionary. Each key-value pair is marked with a colon between the key and value, and each pair is separated by a comma, as shown in the following code example:

example_dict = {'a' :1, 'b' :2, 'c' :3} 

When this expression runs, the result is a dictionary object containing the keys and their values. We can also use the dict class to create dictionary objects:

another_dict = dict() 

If we don't want to use the special syntax to access one of the stored values in a dictionary, we use a lookup expression. This means that we place square brackets containing the key we want to look up after an expression that gives us the dictionary. Usually, this means, the name of the variable containing the dictionary, an open square bracket, a sub-expression that gives us the key, and then a closing square bracket:

example_dict['b'] 
2 

We can also use the dict.get function if we prefer not to use the special syntax:

example_dict.get('c') 
3 
主站蜘蛛池模板: 怀宁县| 容城县| 屏东县| 寻乌县| 余江县| 荔浦县| 同心县| 库车县| 安西县| 达孜县| 洛隆县| 上杭县| 始兴县| 贡嘎县| 铅山县| 康保县| 房产| 武川县| 沭阳县| 交口县| 沁水县| 兴山县| 盈江县| 搜索| 榆社县| 文安县| 阿图什市| 凤庆县| 柯坪县| 阳朔县| 吉首市| 土默特右旗| 齐河县| 乌苏市| 辽中县| 北宁市| 綦江县| 高青县| 沙坪坝区| 襄汾县| 同江市|