字典有关

笔记:

1、字典是Python中唯一的映射类型
2、字典包含两个要素:键(key)和值(value)他们是成对出现的,用大括号括起来,多对存在时用逗号隔开。
3、改变字典中的某个值:dict2[key] = ‘value’,插入的方法类似

一、使用dict()函数创建字典
第一种:创建空字典

>>> dict1=dict()
>>> dict1
{}

第二种:关键字参数
dict2 = dict(key1 = value1,key2 = value2),则最后的形式为:
dict2 = {key2:value2,key1:value1}Python的dict是无序的。

>>> dict2 = dict(one = 1,two = 2,three = 3)
>>> dict2
{'one': 1, 'two': 2, 'three': 3}

!!!!!!!!!!!!!注意以下方法会出错:

>>> dic2 = dict(1 = "one",2 = "two",3 = "three")
SyntaxError: invalid syntax

第三种:dict(list)

>>> list1 = [(1,"one"),(2,"two"),(3,"three")]
>>> dict3 = dict(list1)
>>> dict3
{1: 'one', 2: 'two', 3: 'three'}

第四种:dict(tuple)

可以用dict()直接创建字典,如dict1 = dict(((‘F’,70),(‘i’,105),(’s’,115),(‘h’,104),(‘C’,67))),创建出来的字典dict1的形式为{(‘F’,70),(‘i’,105),(’s’,115),(‘h’,104),(‘C’,67)}

>>> tup = ((1,"one"),(2,"two"),(3,"three"))
>>> dict4 = dict(tup)
>>> dict4
{1: 'one', 2: 'two', 3: 'three'}

第五种:dict(zip())

>>> t = zip([1,2,3,],[4,5,6,])
>>> t
<zip object at 0x0000000002FD4788>
>>> list(t)
[(1, 4), (2, 5), (3, 6)]
>>> dict5 = dict(t)
>>> dict5
{}
>>> dict5 = dict(zip([1,2,3,],[4,5,6,]))
>>> dict5
{1: 4, 2: 5, 3: 6}

第六种:dict.fromkeys( list , var )
注意第二个参数var,只能是一个变量

>>> dict.fromkeys(range(3),9)
{0: 9, 1: 9, 2: 9}
>>> dict.fromkeys(range(1,3),["one","two",])
{1: ['one', 'two'], 2: ['one', 'two']}

注意zip()函数:

>>> t = zip([1,2,3,],[4,5,6,])
>>> t
<zip object at 0x0000000002FD4788>
>>> list(t)
[(1, 4), (2, 5), (3, 6)]

二、一些常用方法
0. keys() \ values()\items()

1.copy()

>>> d = dict(zip([1,2,3],["one","two","three"]))
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> temp1 = d.copy()
>>> temp1
{1: 'one', 2: 'two', 3: 'three'}
>>> temp2 = d
>>> temp2
{1: 'one', 2: 'two', 3: 'three'}
>>> id(d)
50135256
>>> id(temp1)
50212656
>>> id(temp2)
50135256

2.clear()

>>> d = dict(zip([1,2,3],["one","two","three"]))
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> temp1 = d.copy()

>>> temp2 = d

>>> temp2.clear()
>>> temp2
{}
>>> temp1
{1: 'one', 2: 'two', 3: 'three'}

3.get(key)———->value

>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> d.get(2)
'two'

4.pop(key)

>>> d.pop(2)
'two'
>>> d
{1: 'one', 3: 'three'}

5.popitem()

>>> d
{1: 'one', 3: 'three'}
>>> d.popitem()
(3, 'three')

6.update()

>>> d
{1: 'one', 3: 'three'}
>>> d.popitem()
(3, 'three')
>>> c = {2:"two"}
>>> d.update(c)
>>> d
{1: 'one', 2: 'two'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值