Python初学教程:Python dict使用示例,pythondict,Python Dict
Python初学教程:Python dict使用示例,pythondict,Python Dict
Python Dict 使用示例:
Python中dict是一个重要的常用的内置类。
#!/usr/bin/python# dict定义 用 { key:value,key1:value1 } 的方式定义fred = { 'mike': 456, 'bill': 399, 'sarah': 521 }# 通过key获得值用fref[key]try: print fred print fred['bill'] print fred['nora'] print "Won't see this!"except KeyError, rest: print "Lookup failed:", restprint# 可以添加或者更新键值对fred['bill'] = 'Sopwith Camel'fred['wilma'] = 2233# 可以通过del删除某个键值对del fred['mike']print fredprint# 通过keys()方法可以获得所有的键print fred.keys()for k in fred.keys(): print k, "=>", fred[k]print# 可以通过has_key(t)判断字典中是否包含指定键for t in [ 'zingo', 'sarah', 'bill', 'wilma' ]: print t, if fred.has_key(t): print '=>', fred[t] else: print 'is not present.'
python中的dict类是一种键值对的集合,这和java中的HashMap类很像。 注意dict的key必须是不可变的,但是要注意tuple虽然是不可变的,但是它作为字典的键时不能包含可变的元素。
相关内容
- Python初学教程:读取文件,,Python 读取文件#
- Python 操作 Sqlite3教程,pythonsqlite3,Python编程语言从出
- Python生成RSS,pythonrss,心血来潮要搞下pytho
- Python解析RSS,pythonrss,首先需要安装RSS解析的
- python webpy purge nginx fastcgi cache 代码实现,webpynginx,前几
- Python初学教程:Python使用os.path处理文件路径,pythonos
- Python验证Url地址的正则表达式,python正则表达式,Pytho
- Python连接mysql OperationalError: (1366, "Incorrect string
- Python使用easy_install升级包,pythoneasy_install,easy_install
- Python实现java或者.net的getHashCode()函数,pythongethashcode,
评论关闭