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}
"""

 

转载于:https://www.cnblogs.com/zhengws/articles/6675802.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值