首页 > 代码库 > Python学习心得(二) 字典Dictionary

Python学习心得(二) 字典Dictionary

 

 

 前言 . 在Python中字典就是一系列的键值对,一种可变容器,可以存储任意对象,也被称作关联数组或哈希表。


1.基本语法
   用一对花括号{}中的一系列键值对表示,键与值之间用冒号分隔,键值对之间用逗号分隔,例如:

blogger = {‘name‘: ‘binguo‘,‘age‘: 27}

2.访问字典中的值

print ‘name:‘+ blogger[‘name‘] +‘ age:‘ +str(blogger[‘age‘])

3.添加键值对

blogger[‘gender‘] = ‘male‘
print blogger #{‘gender‘: ‘male‘, ‘age‘: 27, ‘name‘: ‘binguo‘}

4.修改字典中的值

blogger[‘name‘] = ‘binguo168‘
print blogger[‘name‘] #binguo168

5.删除键值对

del blogger[‘age‘]
print blogger #{‘gender‘: ‘male‘, ‘name‘: ‘binguo168‘}

6.遍历所有的键值对

for key,value in blogger.items():
    print ‘\nkey:‘+key
    print ‘value:‘+value
‘‘‘
key:gender
value:male

key:name
value:binguo168
‘‘‘ 

7.遍历字典中所有的键

for key in blogger.keys():
    print ‘key:‘+key
"""
key:gender
key:name
"""   
#按顺序遍历字典中所有的键
for key in sorted(blogger.keys()): #对blogger.keys()方法调用了 临时性排序函数sorted()
    print ‘key:‘+key

8.遍历字典中所有的值

for value in blogger.values():
    print ‘value:‘+value    
"""
value:male
value:binguo168
"""
#当字典中含有重复元素时,可以集合(set)予以处理,比如:
blogger[‘NameUsedBefore‘] = ‘binguo168‘
#此时blogger字典的value值中就出现了重复元素:[‘male‘, ‘binguo168‘, ‘binguo168‘]
print blogger.values() 
#通过转换集合的方式,剔除了重复元素
for newvalue in set(blogger.values()):
    print newvalue 
"""
binguo168
male
"""

9.嵌套(列表中嵌套字典、字典中嵌套列表、字典中嵌套字典)

blogger2 = [{‘name‘:‘bingru‘,‘age‘:26},{‘company‘:‘csdn‘,‘salary‘:‘you guess‘}]
for message in blogger2:
    print message
#字典嵌套列表
blogger3 ={‘personmessage‘:[‘binguo‘,‘male‘,‘27‘],‘hobby‘:‘study‘}
for key3,value3 in blogger3.items():
    print ‘\nkey3:‘ + key3
    print value3 
#字典嵌套字典
bloggers = {‘binguo‘:{‘gender‘:‘male‘,‘age‘:27},
            ‘binguo168‘:{‘hobby‘:‘study‘,‘education‘:‘graduate from primary school‘}
            }      
for blogger,blogger_info in bloggers.items():
    print ‘\nblogger:‘ + blogger
    print blogger_info
"""
blogger:binguo168
{‘hobby‘: ‘study‘, ‘education‘: ‘graduate from primary school‘}

blogger:binguo
{‘gender‘: ‘male‘, ‘age‘: 27}
""" 

参考资料 《Python编程从入门到实践》   

  

  

 

  

Python学习心得(二) 字典Dictionary