列表和字典遍历

dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
dict["w"]="watermelon"
del(dict["a"])
dict["g"]="grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict
print


#字典的遍历
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
for k in dict:
    print"dict[%s]="% k,dict[k]
print
print


#字典items()的使用
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
#每个元素是一个key和value组成的元组,以列表的方式输出
print dict.items()
print
print


#调用items()实现字典的遍历
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
for(k,v) in dict.items():
    print"dict[%s]="% k,v
print
print


#调用iteritems()实现字典的遍历
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
print dict.iteritems()
for k,v in dict.iteritems():
    print"dict[%s]="% k,v
for (k,v) in zip (dict.iterkeys(),dict.iteritems()):
    print"dict[%s]="%k,v
print
print
#使用列表、字典作为字典的值
dict={"a":("apple",),"bo":{"b":"banana","o":"orange"},"g":["grape","grapegruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]

print dict["g"][1]


===================== RESTART: C:/Python27/dict,list.py =====================
banana
{'w': 'watermelon', 'o': 'orange', 'g': 'grapefruit'}
{}


dict[a]= apple
dict[b]= banana
dict[o]= orange
dict[g]= grape




[('a', 'apple'), ('c', 'grape'), ('b', 'banana'), ('d', 'orange')]




dict[a]= apple
dict[b]= banana
dict[o]= orange
dict[g]= grape




<dictionary-itemiterator object at 0x02D10720>
dict[a]= apple
dict[c]= grape
dict[b]= banana
dict[d]= orange
dict[a]= ('a', 'apple')
dict[c]= ('c', 'grape')
dict[b]= ('b', 'banana')
dict[d]= ('d', 'orange')




('apple',)
apple
{'b': 'banana', 'o': 'orange'}
orange
['grape', 'grapegruit']
grapegruit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值