现在的位置: 首页 > 综合 > 正文

Python中Dictionaries浅析

2013年12月11日 ⁄ 综合 ⁄ 共 1214字 ⁄ 字号 评论关闭

         Python中的dict 类型是一个数据字典(一个以字符串为索引的矩阵)。它由一系列无序的 key-value对组成,能够提供非常快的key检索功能。keys是不能够被改变的类型,它可以是python中的string,a number,或者是一个Tuple;value可以是任何类型的,包括自定义类型,可以是一个任意嵌套的数据结构。它与Perl中的hash,jave中的HashMap,C++中的unordered_Map非常类似。

         dict类型是使用“{}”为标识的。其数值类型为key-value类型。

         >>> insects = {"Dragonfly": 5000, "Praying Mantis": 2000, "Fly": 120000, "Beetle": 350000}

         >>> insects

         {'Fly': 120000, 'Dragonfly': 5000, 'Praying mantis': 2000, 'Beetle': 350000}

         >>> insects["Dragonfly"]

         5000

         >>> insects["Grasshopper"] = 20000

         >>> insects

         {'Fly': 120000, 'Dragonfly': 5000, 'Praying mantis': 2000, 'Grasshopper': 20000, 'Beetle': 350000}

         >>> del insects["Fly"]

         >>> insects

         {'Dragonfly': 5000, 'Praying mantis': 2000, 'Grasshopper': 20000, 'Beetle': 350000}

         >>> insects.pop("Beetle")

         350000

         >>> insects

         {'Dragonfly': 5000, 'Praying mantis': 2000, 'Grasshopper': 20000}

         可以采用dict方法来创建dict类型

         >>> vitamins = dict(B12 = 1000, B6 = 250, A = 380, C = 5000, D3 = 400)

         >>> vitamins

         {'A': 380, 'C': 5000, 'B12': 1000, 'D3': 400, 'B6': 250}

         可以采用tuple来实现disc的keys

         >>> points3d = {(3, 7, -2): "Green", (4, -1, 11): "Blue", (8,15, 6): "Yellow"}

         >>> points3d

         {(4, -1, 11): 'Blue', (8,15, 6): 'Yellow' ,(3, 7, -2): 'Green'}

         >>> points3d[(8, 15, 6)]

         'Yellow'

抱歉!评论已关闭.