python字典

#!/usr/bin/python
#encoding=utf-8

dict={}  
dict['x'] = 1

dict1 = {'x':1, 'y':2, 'z':3}

print dict1
#'x':1, 'y':2, 'z':3

for i in dict1.keys():
print i

for i in dict2.values():
print i

for i in dict2.items():
print i

print 'x' in dict1 #True
print 'xx' in dict1 #False


print dict1.get('x')
#1, 对应的value值

print dict1.get(32, 'error')
#error

print dict1.get(32)
None

#清空字典
dict1.clear()

#移出一对key-values
dict1.pop('x')

#插入一对key-values
dict1.setdefault('xx', 4)

#修改value值
b = {'xx', 44}
dict1.update(b)

#pickle模块
#将对象转化为二进制,并存储到文件,注意打开需要是二进制读写
import pickle

pickle = open('mypick.pck', 'wb')
mylist = [1,2, 4, [1,2, 4]]

pickle.dump(mylist)

pickle.close()

pickle = open('mypick.pck', 'rb')
mylist = []
mylist = pick.load(pickle)

print mylist #[1,2, 4, [1,2, 4]]

 

posted on 2015-11-29 20:14  阳台  阅读(244)  评论(0编辑  收藏  举报

导航