python哪个代码是正确的字典_Python - 字典(dict) 详解 及 代码
字典(dict) 詳解 及 代碼
本文地址:?http://blog.csdn.net/caroline_wendy/article/details/17291329
字典(dict)是表示映射的數據結構,key-value形式, key必須是唯一的;
items()方法, 返回字典的所有項;
可以通過for循環去遍歷字典的鍵(key)和值(value), 也可以使用if判斷元素是否存在;
可以通過len()求字典的長度;下標操作符("[]")增加和刪除元素;
代碼:
# -*- coding: utf-8 -*-
#====================
#File: abop.py
#Author: Wendy
#Date: 2013-12-03
#====================
#eclipse pydev, python3.3
#字典, 即map, dict
an = { 'Caroline' : 'A beautiful girl.',
'Wendy' : 'A talent girl.',
'Spike' : 'A good boy'
}
print (an)
print ("Who is Caroline?", an['Caroline'])
del an['Spike']
print('There are {0} girls.'.format(len(an)))
for name, property in an.items() : #遍歷字典的項
print('{0} is that {1}'.format(name, property))
an['Ruby'] = 'A pretty girl'
if 'Ruby' in an : #判斷元素是否存在
print("The new one Ruby is that", an['Ruby'])
輸出:
{'Caroline': 'A beautiful girl.', 'Wendy': 'A talent girl.', 'Spike': 'A good boy'}
Who is Caroline? A beautiful girl.
There are 2 girls.
Caroline is that A beautiful girl.
Wendy is that A talent girl.
The new one Ruby is that A pretty girl
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python哪个代码是正确的字典_Python - 字典(dict) 详解 及 代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python script文件夹在哪_P
- 下一篇: python代码调试快捷键_6. Pyc