python中的字典_Python中的字典

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:

句法:

<Name of the Dictionary >= {<key1> : <Value1> , <key2> : <Value2>,...., <key n> : <Value n> }

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)
<type 'dict'>

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 1
PYTHON 9
SHELL 3
LINUX 2
>>> 

 For more information on dictionaries please visit :

有关字典的更多信息,请访问:

https://www.python.org/doc/ https://www.python.org/doc/

翻译自: https://www.experts-exchange.com/articles/15479/Dictionaries-in-Python.html

python中的字典

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值