本文共 2174 字,大约阅读时间需要 7 分钟。
python中的字典
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma. In python we can define dictionaries using dictionary construct.
字典包含键:值对。 这意味着具有属性名称和赋值的元组的集合。 每个键与值之间的分号和带有值的属性之间用逗号分隔。 在python中,我们可以使用字典构造来定义字典。
First of all we need to define a dictionary:
首先,我们需要定义一个字典:
Syntax:
句法:
= { : , : ,...., : }
From the above syntax the value can be integer may not be enclosed by single/double quotes and separated by commas.
根据上述语法,该值可以是整数,不能用单引号/双引号引起来,而用逗号分隔。
Example:
例:
>>> COURSE ={'ORACLE': 1 ,'LINUX' : 2, 'SHELL' : 3 ,'PERL' : 4 }>>> type(COURSE)
The dictionaries are also case sensitive. We can access the above dictionary as like below:
字典也区分大小写。 我们可以像下面这样访问上面的字典:
>>> COURSE{'ORACLE': 1, 'PERL': 4, 'SHELL': 3, 'LINUX': 2}
If we want to display the value specifically then we can call the dictionary by each key as like below:
如果要具体显示该值,则可以按每个键调用字典,如下所示:
>>> COURSE ['PERL']4
Now if we want to add another element let say ‘PYTHON’ as value 4 then use as below:
现在,如果我们要添加另一个元素,请说“ PYTHON”作为值4,然后按如下所示使用:
>>> COURSE ['PYTHON'] = 4>>> COURSE{'ORACLE': 1, 'PERL': 4, 'PYTHON': 4, 'SHELL': 3, 'LINUX': 2}>>>
Now if I want to change the value of the key Linux then we have to use as like below:
现在,如果我想更改密钥Linux的值,则必须使用如下所示的代码:
>>> COURSE ['PYTHON'] = 9>>> COURSE{'ORACLE': 1, 'PERL': 4, 'PYTHON': 9, 'SHELL': 3, 'LINUX': 2}>>>
>>> COURSE.keys()['ORACLE', 'PERL', 'PYTHON', 'SHELL', 'LINUX']>>> COURSE.values()[1, 4, 9, 3, 2]
For deleting the key value pair from the dictionary created then we have to use :
为了从创建的字典中删除键值对,我们必须使用:
>>> del COURSE['PERL']>>> COURSE{'ORACLE': 1, 'PYTHON': 9, 'SHELL': 3, 'LINUX': 2}>>>
Let us see how we can loop the dictionary values:
让我们看看如何循环字典值:
>>> for key,val in COURSE.iteritems(): print key,val ORACLE 1PYTHON 9SHELL 3LINUX 2>>>
For more information on dictionaries please visit :
有关字典的更多信息,请访问:
翻译自:
python中的字典
转载地址:http://djhzd.baihongyu.com/