首页
登录 | 注册

Python的字典及内置函数

创建字典的不同方式

a=dict(one=1,two=2,three=3)
b={"one":1,"two":2,"three":3}
c=dict(zip(['one','two','three'],[1,2,3]))
d=dict([('two',2),('one',1),('three',3)])
e=dict({'three':3,'one':1,'two':2})

print(a==b==c==d==e)

 

字典推导式生成

dial_dodes=[
    (86,'china'),
    (91, 'India'),
    (1, 'United States'),
     (62, 'Indonesia'),
   (55, 'Brazil'),
    (92, 'Pakistan'),
     (880, 'Bangladesh'),
     (234, 'Nigeria'),
    (7, 'Russia'),
     (81, 'Japan'),
    
]

country_code={country:code for code,country in dial_dodes}

 

python的字典是一系列键值对。{}

ex  info={'mother':'meat','father':'apple','brother':'fish','me':'water'}

访问指定键元素: print(info['mother'])

添加键值:info['aunt']='banana'

通常先建立一个空字典,在添加键值对  info{}

修改值:info['me']='wahaha'

删除键值: del info['me'] (KeyError )(访问不存在的键值。例如删除轴在访问 info['me'])

遍历字典:

遍历所有的键值:

for k,v in info.items():
print('key='+k)

print('value='+v)

print(info.items()):

dict_items([('mother', 'meat'), ('father', 'apple'), ('brother', 'fish'), ('me', 'wahaha')])

遍历所有的健:

for k in info.keys():

print('key='+k.title())

遍历所有的值

for v in info.values():

print('value='+v.title())

按顺序遍历所有的健:

for k in sorted(info.keys()):

        print(k.title())

 

 

len(info)  返回字典的键值对数

 info={'mother':50,'father':52,'brother':17,'me':23} 

ss=(str(info))   把字典转化为字符串形式

例如 print(ss[0:6])    输出“{moth"

info.clear()  删除所有的键值对,info=[]

a=info.copy()  a copy info所有的键值对

type(info )  返回<class 'dict'>

 

info={'mother':50,'father':52,'brother':17,'me':23}

print('uncle' in info)  返回FALSE

print('me' in info)  返回True

 

 

info.get('me'): 查看‘me’的值是多少,不存在返回NONE

print(info.get('me')) 返回23

print(info.get('uncle')) 返回None

 

info={'mother':50,'father':52,'brother':17,'me':23}

info.setdefault('cousin',59)    类似info.get() 但是 当cousin不存在时生产新的键值对

>>info={'mother':50,'father':52,'brother':17,'me':23,'cousin':'59'}

but info.setdefault('mother',59)  

>>>>info={'mother':50,'father':52,'brother':17,'me':23'}

info.pop('me')

info={'mother':50,'father':52,'brother':17,'me':23}
a=info.pop('me')    >>a=23
print(info)    info>>info={'mother':50,'father':52,'brother':17}

info={'mother':50,'father':52,'brother':17,'me':23}
a=info.pop('cousin')
print(a)
print(info)   报错,返回 KeyError

 

 

 

 

 

 

 

 

 



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.008 s.
京ICP备10005923号