字典是python内建的数据类型
dic = { "name":"wuyn", "gender":"male", "tel":"134338xxxx8" }
字典的keys()方法返回由所有关键字组成的链表,该链表的顺序不定。
keys = dic.keys() 返回 [ name, gender, tel ]
字典的has_key()方法可以检查字典中是否存在某一关键字。
print dic.has_key("name") #True
print dic.has_key("mail") #False
遍历字典中所有属性的值:
keys = dic.keys()
for key in keys:
if dic.has_key(key):
print "%s:%s" % ( key, dic[key] )
-----------------------------------------------------------------------------
字符串转为字典又该如何呢?
import json #(注意是2.6 版本以上)
str = '{"name":"wuyn","tel":"134338xxxx8","mail":wuyn@xxweb.com"}'
dic = json.loads(str)
keys = dic.keys()
for key in keys:
print "%s:%s" % ( key, dic[key] )
--------------------------------------------------------------------------------
items()方法遍历字典
dic = { "name":"wuyn", "gender":"male", "tel":"134338xxxx8" }
for k , v in dic.items():
print "%s:%s" % (k, v)
其实用items()方法获得是是一个序列,可通过下标访问:
eg:
print dic.items()[0] 返回 (u'tel': u'134338xxxx8')
print dic.items()[0][0] 返回 tel
print dic.items()[0][1] 返回 134338xxxx8
dic = { "name":"wuyn", "gender":"male", "tel":"134338xxxx8" }
字典的keys()方法返回由所有关键字组成的链表,该链表的顺序不定。
keys = dic.keys() 返回 [ name, gender, tel ]
字典的has_key()方法可以检查字典中是否存在某一关键字。
print dic.has_key("name") #True
print dic.has_key("mail") #False
遍历字典中所有属性的值:
keys = dic.keys()
for key in keys:
if dic.has_key(key):
print "%s:%s" % ( key, dic[key] )
-----------------------------------------------------------------------------
字符串转为字典又该如何呢?
import json #(注意是2.6 版本以上)
str = '{"name":"wuyn","tel":"134338xxxx8","mail":wuyn@xxweb.com"}'
dic = json.loads(str)
keys = dic.keys()
for key in keys:
print "%s:%s" % ( key, dic[key] )
--------------------------------------------------------------------------------
items()方法遍历字典
dic = { "name":"wuyn", "gender":"male", "tel":"134338xxxx8" }
for k , v in dic.items():
print "%s:%s" % (k, v)
其实用items()方法获得是是一个序列,可通过下标访问:
eg:
print dic.items()[0] 返回 (u'tel': u'134338xxxx8')
print dic.items()[0][0] 返回 tel
print dic.items()[0][1] 返回 134338xxxx8