Posted in Python onOctober 25, 2019
本文实例总结了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:6key:cg
value:365key: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
cmx['java', 'python']
java
python
#字典中存储字典:
#暂略
希望本文所述对大家Python程序设计有所帮助。
Python字典常见操作实例小结【定义、添加、删除、遍历】
- Author -
鲸落丶声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@