文档目录:
一、一个简单的字典
二、字典-增删改
三、遍历字典
四、字典嵌套
—————————————分割线:正文——————————————————–
一、一个简单的字典
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\'))
查看结果
green5
2、更新字典
alien_0={\'color\':\'green\',\'point\':5}alien_0[\'x_postion\']=0alien_0[\'y_postion\']=25alien_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:colorvalue:greenkey:pointvalue:5
2、遍历字典的所有键
alien_0={\'color\':\'green\',\'point\':5}for a in alien_0.keys():print(f\"key:{a}\")
查看结果:
key:colorkey:point
3、遍历字典的所有值
alien_0={\'color\':\'green\',\'point\':5}for a in alien_0.values():print(f\"value:{a}\")
查看结果:
value:greenvalue: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:1key:2key: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\']}myok1myok2
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:yellowpoint:10