python中字典的索引是什么_Python中的字典索引 | 學步園

Python中的符合數據類型:字符串,列表和序列。它們用整數作為索引。如果你試圖用其他的類型做索引,就會產生錯誤。

>>> list = [1 ,2,3]

>>> list[0]

1

>>> list['one']

Traceback (most recent call last):

File "", line 1, in

list['one']

TypeError: list indices must be integers, not str

字典的索引可以是字符串,除了這一點,它與其組合類型非常相似。當然,字典的索引也可以是整數。

>>> dict1 = {'mother':'媽媽','father','爸爸'}

SyntaxError: invalid syntax

>>> dict1 = {'mother':'媽媽','father':'爸爸'}

>>> dict1

{'father': '爸爸', 'mother': '媽媽'}

我們也可以創造一個空字典然後在添加元素。

>>> eng2sp = {}

>>> eng2sp['one'] = 'uno'

>>> eng2sp['two'] = 'dos'

>>> eng2sp

{'one': 'uno', 'two': 'dos'}

字典元素以逗號作為分隔符,每個元素包含鍵和鍵值,他們倆用冒號進行分割

字典的刪除

>>> inventory = {'apples':430,'bananas':312,'oranges':525}

>>> inventory

{'bananas': 312, 'apples': 430, 'oranges': 525}

>>> del inventory['apples']

>>> inventory

{'bananas': 312, 'oranges': 525}

如果你想刪除所有的元素,可以使用clear方法

>>> inventory.clear

>>> inventory

{'bananas': 312, 'oranges': 525}

>>> inventory.clear()

>>> inventory

{}

使用函數len返回字典元素的數量

>>> os = {1:'Linux',2:'Windows'}

>>> len(os)

2

字典是可以改變的,如果你想修改字典,並且保留原來的備份,就要用到字典的copy方法,看看下面的例子:

>>> opp = {'up':'down','right':'left','true':'false'}

>>> alias = opp

>>> alias

{'right': 'left', 'up': 'down', 'true': 'false'}

>>> id(opp)

53056584

>>> id(alias)

53056584

>>> other = opp.copy()

>>> other

{'right': 'left', 'up': 'down', 'true': 'false'}

>>> id(other)

52898824

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值