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

Dictionaries 

A dictionary, like an array, is a collection of items; however, the items in a dictionary are referenced by strings called keys, rather than their order in a list. Another way to think of a dictionary is as a collection of key-value pairs, where the keys are used to retrieve the values.

To create a dictionary, use the following syntax where <key1>, <key2> are strings and value1, value2 are any values:

{<key1>:<value1>,<key2>:<value2>,<key3>:<value3>}
Notice that a dictionary has curly brackets whereas an array has square brackets.

The following line will create a dictionary called d with two key-value pairs:

>> d = {"some_number": 1, "sup?": "yo!"}
>> print(d)

You can access a specific value of a dictionary using the following syntax:

<dictionary name>[<key>]

For example:

>> print(d["sup?"])
>> print(d["some_number"])

You can also set the value of a key by assigning a value to that key, as the following demonstrates:

>> d["some_number"] = 5
>> print(d["some_number"])

If you assign a value to a key that does not yet exist in a particular dictionary, the key will be added to the dictionary:

>> d["new_key"] = "I'm a new value"
>> print(d["new_key"])

On an intuitive level, the big advantage of Python dictionaries comes from the ability to store and reference items by key. It is easier to remember a name than a number. If, for example, you are working with a spreadsheet that has 100 columns, it is much more convenient to retrieve an entry by its column header than its position.

主站蜘蛛池模板: 丰镇市| 武隆县| 梁河县| 类乌齐县| 桐梓县| 阜平县| 台北市| 衡阳县| 迁安市| 湘乡市| 霍林郭勒市| 东阳市| 乌什县| 台东市| 扬州市| 延长县| 黑河市| 石屏县| 鄂伦春自治旗| 剑河县| 罗源县| 和田市| 舒城县| 离岛区| 遂平县| 明光市| 阜宁县| 泾源县| 鄂托克旗| 鹤岗市| 余庆县| 伊通| 上思县| 中西区| 基隆市| 习水县| 台山市| 葫芦岛市| 宾川县| 卢龙县| 会宁县|