python

超轻量级php框架startmvc

Python字典常见操作实例小结【定义、添加、删除、遍历】

更新时间:2020-08-04 21:18:01 作者:startmvc
本文实例总结了Python字典常见操作。分享给大家供大家参考,具体如下:简单的字典:字典

本文实例总结了Python字典常见操作。分享给大家供大家参考,具体如下:

简单的字典:

字典就是键值对key-value组合。


#字典 键值对组合
alien_0 ={'color':'green','number':5}
print(alien_0['color'])
print(alien_0['number'])

运行结果:

green 5

添加键值对


alien_0 ={'color':'green','number':5}
alien_0['first_name'] = 'mo'
alien_0['last_name'] = 'ak'
print(alien_0)

运行结果:

{'color': 'green', 'number': 5, 'first_name': 'mo', 'last_name': 'ak'}

使用字典:


#访问元素
favorite_languages ={
 'jen':'python',
 'sarah':'c',
 'edwoad':'ruby',
 'phil':'python',
}
print(favorite_languages['jen'])
#删除键值对
del favorite_languages['phil']
print(favorite_languages)

运行结果:

python {'jen': 'python', 'sarah': 'c', 'edwoad': 'ruby'}

遍历字典:


favorite_numbers = {
 'mx' : '6',
 'cg' : '365',
 'zxp': '8',
}
for key,value in favorite_numbers.items():
 print("\nkey:"+key)
 print("value:"+value)

运行结果:

key:mx value:6

key:cg value:365

key:zxp value:8

遍历字典中的所有键:


favorite_numbers = {
 'mx' : '6',
 'cg' : '365',
 'zxp': '8',
}
for name in favorite_numbers.keys():
 print(name.title())

运行结果:

Mx Cg Zxp

嵌套:


#字典列表:
alien_0 = {'color':'green','points':5}
alien_1 = {'color':'red','points':6}
alien_2 = {'color':'blue','points':3}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
 print(alien)
#字典中存储列表:
favorite_language ={
 'jen':['python','c'],
 'mx':['java','python'],
}
for name,languages in favorite_language.items():
 print("\n\t"+name+str(languages))
 for language in languages:
 print(language)

运行结果:

{'color': 'green', 'points': 5} {'color': 'red', 'points': 6} {'color': 'blue', 'points': 3}

 jen['python', 'c'] python c

 mx['java', 'python'] java python

#字典中存储字典: #暂略

Python 字典 常见操作 定义 添加 删除 遍历