python字典操作

建立一个字典

>>> dict1 = {}
>>> dict2 = {'name': 'earth', 'port':80}
>>> dict2
{'name': 'earth', 'port': 80}
>>> dict1, dict2
({}, {'name': 'earth', 'port': 80})
>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}

>>> ddict = {}.fromkeys(('x', 'y'), -1)
>>> ddict
{'y': -1, 'x': -1}
>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}

遍历字典:

>>> for key in dict2.keys():
...     print 'key = %s, value = %s' % (key, dict2[key])
...
key = name, value = earth
key = port, value = 80


>>> for key in dict2.keys():
...     print 'key = %s, value = %s' % (key, dict2[key])
...
key = name, value = earth
key = port, value = 80

显示字典的某个元素的值:

>>> dict2['name']
'earth'
>>> dict2['port']
80


字典的方法:

>>> 'earth' in dict2
False
>>> 'name' in dict2
True
>>> 'server' not in dict2
True
>>> 'name' not in dict2
False

>>> dict2.has_key('server')
False
>>> dict2.has_key('name')
True

字典混用数字和字符串:

>>> dict3 = {}
>>> dict3[1] = 'abc'
>>> dict3[2] = 3.14
>>> dict3[3] = 'xyz'
>>> dict3[100] = 100
>>> dict3
{1: 'abc', 2: 3.1400000000000001, 3: 'xyz', 100: 100}
>>> dict3[4] = 'opq'
>>> dict3
{1: 'abc', 2: 3.1400000000000001, 3: 'xyz', 100: 100, 4: 'opq'}

更改字典元素的值:

>>> dict2['name']
'earth'
>>> dict2['name'] = 'moon'
>>> dict2['name']
'moon'

删除:

>>> del dict2['name']
>>> dict2
{'port': 80}
>>> dict2['name'] = 'earth'
>>> dict2
{'name': 'earth', 'port': 80}
>>> dict2.clear()
>>> dict2
{}
>>> del dict2
>>> dict2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict2' is not defined

>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict2
{'name': 'earth', 'port': 80}
>>> dict2.pop('name')
'earth'
>>> dict2
{'port': 80}
>>> dict2.pop('port')
80
>>> dict2
{}

用update()方法把一个字典加入另一个字典

>>> dict2 = {'name': 'earth', 'port': 80}
>>> dict3 = {'ip': '127.0.0.1'}
>>> dict2.update(dict3)
>>> dict2
{'ip': '127.0.0.1', 'name': 'earth', 'port': 80}
>>> dict4 = {'other': 'macos'}
>>> dict2.update(dict4)
>>> dict2
{'ip': '127.0.0.1', 'other': 'macos', 'name': 'earth', 'port': 80}

映射类型( Mapping Types, http://docs.python.org/library/stdtypes.html )

>>> dict(one=1, two=2)
{'two': 2, 'one': 1}
>>> dict({'one': 1, 'two': 2})
{'two': 2, 'one': 1}
>>> dict(zip(('one', 'two'), (1, 2)))
{'two': 2, 'one': 1}
>>> dict([['two', 2], ['one', 1]])
{'two': 2, 'one': 1}

>>> dict8 = dict(x=1, y=2)
>>> dict8
{'y': 2, 'x': 1}
>>> dict9 = dict(**dict8)
>>> dict9
{'y': 2, 'x': 1}
>>> dict9 = dict(dict8)
>>> dict9
{'y': 2, 'x': 1}
>>> dict9 = dict8.copy()
>>> dict9
{'y': 2, 'x': 1}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值