python2之字典

pople = {
    'Alice':{
        'phone': '15897693332',
        'addr': 'a'
    },

    'Beth':{
        'phone': '158',
        'addr': 'b'
    },

    'Cell': {
        'phone': '3332',
        'addr': 'c'
    }
}
#标签
lables = {
    'phone' : 'phone number',
    'addr' : 'address'
}

name = raw_input('plase input your name:')
request = raw_input('Phone is p, Address os a: ')

if request == 'p': 
    key = 'phone'
if request == 'a': 
    key = 'addr'

if name in pople : 
    print "%s's %s is %s" \
     %(name,lables[key],pople[name][key])
格式化输出字典
people = {
    "A": 'a',
    "B": 'b',
    "C": 'c'
}
print "C key is %(C)s" % people
##输出
#C key is c
HTML示例
template = """
    <html>
    <head><title>%(title)s<title><head>
    <body>
    <h1>%(title)s<h1>
    <p>%(test)s<p>
    <body>
"""

data = {
    "title": "Home",
    "test": "this is my home"
}
print template % data

##输出
#
#    <html>
#    <head><title>Home<title><head>
#    <body>
#    <h1>Home<h1>
#    <p>this is my home<p>
#    <body>
#

模板字符串

"""
	string 模板提供另外一种格式化值的方式, 模板字符串, 
	substitute这个模板方法会传递进来的关键字参数foo替换字符串中的$foo
"""
from string import Template
s = Template("$x world \n,$x school")
print s.substitute(x='hello')
##输出
#hello world 
#,hello school
-------------------------------------------------
# 使用字典初始化字符串
from string import Template
s = Template("$a world \n,$b school")
data = {
    'a': "hello",
    'b': "hi"
}
print s.substitute(data)
--------------------------------------------------
from string import Template
s = Template("$a world \n,$b school,$c")
data = {
    'a': "hello",
    'b': "hi"
}
print s.substitute(data)
#error错误, 参数个数缺少
#使用
print s.safe_substitute(data)
##输出
#hello world 
#,hi school,$c

清空子典
x = {'1':1, '2':2, '3':3}
y = x
print x,'\n',y

x = {}
print x,'\n',y
##输出
#{'1': 1, '3': 3, '2': 2} 
#{'1': 1, '3': 3, '2': 2}
#{} 
#{'1': 1, '3': 3, '2': 2}
#y并没有清楚, 而只是把一个空的字典赋值给了x
y.clear()
print x,'\n',y
#x,y全部为空
拷贝
##python 浅拷贝和深拷贝
#copy
x = {'1':1, '2':2, '3':['a',2]}
y = x.copy()

y['1'] = 3
y['3'].remove(2)
print x,'\n',y
##输出
#{'1': 1, '3': ['a'], '2': 2} 
#{'1': 3, '3': ['a'], '2': 2}
#
#浅拷贝如果单纯只是数据替换那么原数据不会受到影响
#如果是移除修改了某个值那么原始也会产生改变
--------------------------------------

#deepcopy
from copy import deepcopy
x = {'1':1, '2':2, '3':['a',2]}
y = deepcopy(x)

y['1'] = 3
y['3'].remove(2)
print x,'\n',y
##输出
#{'1': 1, '3': ['a', 2], '2': 2} 
#{'1': 3, '3': ['a'], '2': 2}
#
#数据并没有移除
对给定的键建立相应的字典
## fromkeys
ls = ['1', '2']
dr = dict.fromkeys(ls,"unknown")
##输出
#{'1': 'unknown', '2': 'unknown'}
#默认是 None, 如果需要修改默认可以在第二个参数修改
get
# 如果试图访问不存在的字典元素那么会报错
# 但是get方法不会, 他会返回一个空值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值