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

Working with dictionaries

There are a large number of methods that can be used with dictionaries.

We won't talk about all of them, but some of the more common ones are shown in the following screenshot:

Dictionary methods

Line 36 checks to see whether a specified key exists within the dictionary.

Line 37 returns all the items that exist within the dictionary—both keys and their associated values. For more flexibility, you can look for just a dictionary's keys (line 38) or just the values (line 39).

To remove entries within a dictionary, you can delete single items, as demonstrated in line 40. To remove all entries in dictionary d1, you would use the d1.clear() method .

Since dictionaries are changeable, you can add and delete values to them without creating a new dictionary object, as shown in lines 23 and 40. Adding a new object to a dictionary only requires making a new key and value, whereas lists will return an index out-of-bounds error if the offset is past the end of the list. Therefore, you must use append() to add values to lists but simply make new key value entries for dictionaries.

The following screenshot is a more realistic dictionary example. The following example creates a table that maps programming language names (the keys) to their creators (the values). You fetch a creator name by indexing on the language name:

Using a dictionary

From this example, you might notice that the last command is similar to string and list iteration using the for command. However, you'll also notice that, since dictionaries aren't sequences (that is, the stored items are indexed by keyword and not position), you can't use the standard for statement. You must use the keys() method to return a list of all the keys which you can then iterate through like a normal list.

You may have also noticed that dictionaries can act like light weight databases. The preceding example creates a table, where the programming language column is matched by the creator's row. If you have a need for a database, you might want to consider using a dictionary instead. If the data will fit, you will save yourself a lot of unnecessary coding and reduce the headaches you would get from dealing with a full-blown database. Granted, you don't have the flexibility and power of a true database, but for quick-and-dirty solutions, dictionaries will suffice.

主站蜘蛛池模板: 陵水| 昆山市| 泗洪县| 黄梅县| 桓仁| 肇庆市| 宁晋县| 金川县| 高碑店市| 二连浩特市| 无极县| 宜丰县| 当雄县| 岳普湖县| 南涧| 沙雅县| 皮山县| 尼木县| 新津县| 汶川县| 五常市| 宝清县| 民丰县| 瑞金市| 巴彦淖尔市| 铜山县| 井陉县| 防城港市| 青田县| 咸丰县| 长岭县| 永清县| 蓬溪县| 屏东县| 巫溪县| 阜阳市| 府谷县| 常山县| 杂多县| 英吉沙县| 松溪县|