Python 字典

python字典的定义采用 {键:值}的方式,字典的实质是映射关系

创建一个字典

>>> dict1={}   #1.创建一个空字典

>>> dict1={"name":"李","sex":"man","city":"成都"}   #2.通过大括号包含键和值
>>> dict1
{'name': '李', 'sex': 'man', 'city': '成都'}

>>> dict2=dict(((1,"one"),(2,"two")))  #3.通过内置函数dict()在内部形成映射关系
>>> dict2
{1: 'one', 2: 'two'}

>>> dict3=dict(名字="李",性别="男",城市="成都") #4.通过内置函数dict()中写入键和值
>>> dict3
{'名字': '李', '性别': '男', '城市': '成都'}
>>> 

字典的索引、添加和删除

字典的访问:

>>> dict3["名字"]     #通过索引键来访问字典的值
'李'

添加:

>>> dict3
{'名字': '李', '性别': '男', '城市': '成都'}
>>> dict3["年龄"]=21
>>> dict3
{'名字': '李', '性别': '男', '城市': '成都', '年龄': 21}
>>> 

删除

>>> dict3.pop("年龄")
21
>>> dict3
{'名字': '李', '性别': '男', '城市': '成都'}

>>> dict2          #将字典清空
{1: 'one', 2: 'two'}
>>> dict2.clear()
>>> dict2
{}

字典访问函数

fromkeys()函数

fromkeys((字典中所有的键),默认值):能将整个字典统一默认值(必须加入字典中所有的键,而且只能默认一个值)


>>> dict4={}
>>> dict4=dict1.fromkeys((1,2,3,4,5),"hello")
>>> dict4
{1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello', 5: 'hello'}

keys()函数

访问字典所有的键

>>> for eachkey in dict4.keys():
	print(eachkey)

	
1
2
3
4
5

values()函数

访问字典中所有的值

>>> for eachvalue in dict4.values():
	print(eachvalue)

	
hello
hello
hello
hello
hello

items()函数

访问所有键值对

>>> for eachitem in dict4.items():
	print(eachitem)

	
(1, 'hello')
(2, 'hello')
(3, 'hello')
(4, 'hello')
(5, 'hello')

集合

(用大括号表示,但其中是单独一个元素并不是键值对)

集合里的元素都是唯一的只能出现一次

>>> a={1,1,2,3,4}
>>> a
{1, 2, 3, 4}
>>> a=set([1,2,2,3,3,4])
>>> a
{1, 2, 3, 4}
>>> type(a)
<class 'set'>

将列表中相同元素去除:


>>> b=[1,2,2,3,3,4,4,5]
>>> b=list(set(b))
>>> b
[1, 2, 3, 4, 5]

集合中元素无序,不能用索引访问

>>> a[1]
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    a[1]
TypeError: 'set' object does not support indexing

元素添加和删除:


>>> a.add(6)
>>> a
{1, 2, 3, 4, 6}
>>> a.remove(6)
>>> a
{1, 2, 3, 4}

frozenset()函数

将集合定义为不可修改

>>> c=frozenset(a)
>>> c.add(10)
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    c.add(10)
AttributeError: 'frozenset' object has no attribute 'add'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值