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

Creating dictionaries

As previously stated, you create dictionaries and access items through a key. The key can be of any immutable type, such as a string, number, or tuple; basically, anything that can't be changed. Each key's associated value can be any type of object, including other dictionaries. The basic use of dictionaries is displayed in the following screenshot:

Basic dictionary operations

Line 19 creates the dictionary. Note that the brackets for dictionaries are curly braces, the separator between a key word and its associated value is a colon, and that each key:value is separated by a comma. In this example, the first mapping is a string to a string, the second is a string to an integer, and the last is a list to an integer.

Line 20 shows how to see how many items are contained within a dictionary. This value is only the number of mappings, not the individual keys/values contained within the dictionary.

Line 21 returns the value associated with the key cow. If you want to add a new item, you have to use the format in line 23—the name of the dictionary, followed by the new key within square brackets, and then what that key is equal to. If you try to make a new dictionary entry by trying to directly map the value to its key through a colon character (line 22), you will get an error.

After the new entry is created in line 23, we can verify it is there by simply calling the dictionary (line 24). Values in dictionary entries are completely accessible; in the case of line 25, we can increment the integer value by directly adding 1 to the appropriate key.

Compare this to lines 21 and 23. In line 21, calling the key returned its associated value. In line 23, adding the = sign to a key made a new dictionary entry. Thus, line 25 acts like a combination of those two—it gets the value associated to a key, and then makes a new dictionary entry by performing an operation on the value. In this case, we are simply adding 1 to the value, and then reassigning it as the key's associated value. Line 26 returns the entire dictionary to show that the new value associated with the chicken key has been incremented from 3 to 4.

主站蜘蛛池模板: 股票| 鸡泽县| 安福县| 新民市| 田东县| 舞阳县| 萍乡市| 科技| 广州市| 麻阳| 会昌县| 托里县| 博兴县| 六盘水市| 金秀| 石林| 宁海县| 博罗县| 定西市| 禄丰县| 嘉黎县| 全州县| 稻城县| 吉隆县| 舞阳县| 连云港市| 柳河县| 凤台县| 容城县| 新蔡县| 万盛区| 壤塘县| 南投县| 红河县| 甘肃省| 惠州市| 诸暨市| 镇宁| 孝昌县| 肥城市| 横山县|