o(* ̄︶ ̄*)o

  博客园  :: 首页  ::  :: 联系 :: 订阅 订阅  :: 管理

python字典

#
# 字典
#

#4-1 字典使用

name = ['Lily', 'Lucy', 'Jim', 'Jane']
tel_num = ['110', '120', '119', '12315']
print tel_num[name.index('Jim')]

#4-2 字典创建和使用
#创建字典
phone = {'Lily':'110', 'LuCY':'120', 'jIM':'119'}
print phone

#空字典
phone = {}
print phone

#@func_name : dict函数
#@func: 将列表组成 字典
item = [('name', 'Jim'), ('phone', '11111')]
d = dict(item)
print d
print d['name']                                    #通过键值查找

#或者
d = dict(name = 'Grubby', kinds = 'orc')
print d

#基本操作
print len(d)             

d['name'] = 'Sky'
print d['name']    

del d['name']
print d

print 'kinds' in d

d['100'] = 1222                                    #数据插入
print d

#ep 字典示例

people = {
	'Alice':{
		'phone':'1110',
		'money':'111'
	},
	
	'Jim':{
		'phone':'1154',
		'money':'111'
	},
	
	'Jine':{
		'phone':'21154',
		'money':'2111'
	},
}

labels = {
	'phone':'phone number',
	'money': 'addr'
}

name = 'Jine'

request = False
if request:
	key = 'phone'
else:
	key = 'money'

if name in people:print "%s's %s is %s." % \
	(name, labels[key], people[name][key])


#特色格式化, 
print "%(phone)s" % labels

#字典方法

#浅拷贝
x = people.copy()
y = people.copy()
y['Jim'] = {}
y['Jine']['phone']= 'XXXXXX'
print x, y                                # 只修改不替换,影响原始字典

#深度拷贝
import copy
x = copy.deepcopy(people)

#访问字典
print u'访问字典'
print people.get('Lily', 'test')         # 找不到值时,使用后者字段 打印出来,不然打印实际值
print people.get('Alice')

#has_key 相当 in
print people.has_key('Lily')
print people.has_key('Alice')

#items, iteritems
print "show data :"
print people.items()
print "show data :"
print list(people.iteritems())
print "show data :"
people.pop('Alice')
print people
print "--------------------------"
people.popitem()
print people

#setdefault 与get相同

#update  将另一个字典元素全部插入到当前字典,如果重复,则覆盖。
people.update({'xiaomi':{'phone': '1234', 'money':'456789'}}	)  
print people

#values 将字典转变成列表
print people.values()

#删除,清理
test = people                        # 相当两个变量 同时指向一个空间
people.clear()                       # 清空 字典
print people
print test                            # test 也是空的,没有拷贝, 字典

#建新字典
print {}.fromkeys(['name', 'age'])    # 自动添加内容 None
print dict.fromkeys(['name', 'age'], '123') # 指定内容 

  

posted on 2015-03-06 18:19  熊本熊の熊  阅读(99)  评论(0)    收藏  举报