Python 字典简单操作

1、字典的常用方法

#clear()清空字典
myDict.clear()
print(myDict)
输出:{}
#get() 获取字典key对应的值,如果不存在key默认情况下返回none,可以进行修改默认值
print(myDict.get('name'))
print(myDict.get('nameaa',123))
输出:
zws
123
#item() 获取字典中的键值对,返回的值为列表,采用iteritems()方法,返回的为迭代器,不直接生成列表,可以减少内存的占用 print(myDict.items())
输出:
dict_items([('weight', 130.25), ('age', 18), ('name', 'zws')])

   print(myDict.iteritems())
   <dictionary-itemiterator object at 0x7fa015db17e0>

#keys()获取字典中的key
print(myDict.keys())
输出:
dict_keys(['weight', 'age', 'name'])
#values()获取字典中的值 print(myDict.values())
输出:
dict_values([130.25, 18, 'zws'])
#pop() 弹出字典中指定key的键值对 myDict.pop('name') print(myDict)
输出:
{'age': 18, 'weight': 130.25}
#popitem() 弹出字典首个键值对,并返回所弹出的键值对,注意:由于字典中元素是无序的,弹出的可能并不是我们想要的键值对,例如,在此弹出的是weight。 myDict.popitem() print(myDict) 输出:
{'name': 'zws', 'age': 18}

tmp
= { 'study':'python', 'merry':'yes' } #更新,往字典前追加tmp字典。 myDict.update(tmp) print(myDict)
输出:
{'study': 'python', 'merry': 'yes', 'age': 18, 'weight': 130.25, 'name': 'zws'}

#fromkeys(seq , values) 组合两个list,成为新的字典。
#调用者可直接采用dict调用
keyList = ['key1', 'key2', 'key3', 'key4', 'key5']
valueList = [1, 2, 3, 4, 5]
tmpDict = dict.fromkeys(keyList, valueList)
print (tmpDict)
输出:
{'key3': [1, 2, 3, 4, 5], 'key2': [1, 2, 3, 4, 5], 'key5': [1, 2, 3, 4, 5], 'key1': [1, 2, 3, 4, 5], 'key4': [1, 2, 3, 4, 5]}
 

二、使用zip函数, 把key和value的list组合在一起, 再转成字典(dict).

# -*- coding: utf-8 -*-
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print dictionary

"""
输出:
{'a': 1, 'c': 3, 'b': 2}
"""

 

posted @ 2017-04-06 22:36  漫舞沧海  阅读(115)  评论(0编辑  收藏  举报