python进阶(4)--字典

文档目录:

一、一个简单的字典
二、字典-增删改
三、遍历字典
四、字典嵌套

---------------------------------------分割线:正文--------------------------------------------------------

一、一个简单的字典

alien_0={'color':'green','point':5}
print(type(alien_0))

查看结果:

<class 'dict'>

 

二、字典-增删改

1、访问字典

alien_0={'color':'green','point':5}
print(alien_0['color'])
print(alien_0.get('point'))

查看结果

green
5

2、更新字典

alien_0={'color':'green','point':5}
alien_0['x_postion']=0
alien_0['y_postion']=25
alien_0['color']='yellow'
print(alien_0)

查看结果:

{'color': 'yellow', 'point': 5, 'x_postion': 0, 'y_postion': 25}

3、删除键值对

alien_0={'color':'green','point':5}
del alien_0['color']
print(alien_0)

查看结果:

{'point': 5}

 

三、遍历字典

 1、遍历字典的键值对

alien_0={'color':'green','point':5}
for a,b in alien_0.items():
    print(f"key:{a}")
    print(f"value:{b}")

查看结果:

key:color
value:green
key:point
value:5

2、遍历字典的所有键

alien_0={'color':'green','point':5}
for a in alien_0.keys():
    print(f"key:{a}")

查看结果:

key:color
key:point

3、遍历字典的所有值

alien_0={'color':'green','point':5}
for a in alien_0.values():
    print(f"value:{a}")

查看结果:

value:green
value:5

4、遍历并去重字典的值

alien_0={'test01':1,'test02':1,'test03':2,'test04':2,'test05':3,'test06':3,}
for a in set(alien_0.values()):
    print(f"key:{a}")

查看结果:

key:1
key:2
key:3

 

四、字典嵌套

1、列表套字典

复制代码
alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
list1=[alien_0,alien_1]
print(list1)
for alien in list1:
    print(alien)
复制代码

查看结果:

[{'color': 'green', 'point': 5}, {'color': 'yellow', 'point': 10}]
{'color': 'green', 'point': 5}
{'color': 'yellow', 'point': 10}

2、字典套列表

testList=['myok1','myok2']
testDict={'task1':'mydict','task2':testList}
print(testDict)
for list1 in testDict['task2']:
    print(list1)

查看结果:

{'task1': 'mydict', 'task2': ['myok1', 'myok2']}
myok1
myok2

3、字典套字典

复制代码
alien_0={'color':'green','point':5}
alien_1={'color':'yellow','point':10}
aliens={'fisrt':alien_0,'second':alien_1}
print(aliens)
for a,b in aliens['second'].items():
    print(f"{a}:{b}")
复制代码

查看结果:

{'fisrt': {'color': 'green', 'point': 5}, 'second': {'color': 'yellow', 'point': 10}}
color:yellow
point:10
posted @   Mrwhite86  阅读(68)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-04-17 软件测试基础
点击右上角即可分享
微信分享提示