dictionary是Python唯一内置的 mapping 数据类型。
>>> logins = {‘yahoo’:(‘john’,’jyahooohn’),
... ‘hotmail’:(‘jrf5’,’18thStreet’)}
>>> logins[‘hotmail’] # What’s my name/password for hotmail?
(‘jrf5’, ‘18thStreet’)
1、Creating and adding to dictionaries
创建一个dictionary,就是通过在花括号中放 0 个或 多个 键值对。
键必须是唯一的、immutable,所以字符串、数字、以及元素是 immutable 的 tuples 都可以担任键。而值可以是任何东西。
添加或替换 mappings 很简单:
>>> logins['slashdot'] = ('juan', 'lemmein')
2、Accessing and updaing dictionary mappings
用一个不存在的 key,Python会抛出 KeyError 异常。当你不想关心处理该异常,那可以用 get(key[, obj])方法,如果映射不不存在的话,它会返回None,当然你可以给它指定一个默认值。
>>> logins[‘sourceforge’,’No such login’]
Traceback (innermost last):
File “<interactive input>”, line 1, in ?
KeyError: (‘sourceforge’, ‘No such login’)
>>> logins.get(‘sourceforge’) == None
1
>>> logins.get(‘sourceforge’,’No such login’)
‘No such login’
setdefault(key[, obj]) 方法和 get 类似,但如果键值对不存在,它会将它们添加到这个 dictionary中去:
>>> logins.setdefault(‘slashdot’,(‘jimmy’,’punk’))
(‘juan’, ‘lemmein’) # Existing item returned
>>> logins.setdefault(‘justwhispers’,(‘jimmy’,’punk’))
(‘jimmy’, ‘punk’) # New item returned AND added to dictionary
如果只是想知道一个 dictionary 是否含有某个键值对,那可以用 has_key(key) 方法:
>>> logins.has_key('yahoo')
1
del 语句会从一个 dictionary 中移除一项:
>>> del logins['yahoo']
>>> logins.has_key('yahoo')
0
=====================“Hashability”=========================
对于 dictionary 的键的最确切的要求是它必须 be hashable。对象的 hash 值用于快速比较。考虑比较两个字符串这件事,要判断2个字符串是否相等,需要比较每个字符直到发现一个不相等的字符。
如果你已经有了每个字符串的 hash 值,那只要比较它们的 hash 值就可以了。Python 在进行 dictionary lookup 时,就利用了 hash 值。
==============================================
可以用 update(dict) 将某个 dictionary 中的元素添加到另一个 dictionary中:
>>> z = {}
>>> z[‘slashdot’] = (‘fred’,’fred’)
>>> z.update (logins)
>>> z
{‘justwhispers’: (‘jimmy’, ‘punk’),
‘slashdot’: (‘juan’, ‘lemmein’), # Duplicate key overwritten
‘hotmail’: (‘jrf5’, ‘18thStreet’)}
3、Additional dictionary operations
>>> len(logins) # How many items?
3
>>> logins.keys() # List the keys of the mappings
[‘justwhispers’, ‘slashdot’, ‘hotmail’]
>>> logins.values() # List the other half of the mappings
[(‘jimmy’, ‘punk’), (‘juan’, ‘lemmein’), (‘jrf5’,
‘18thStreet’)]
>>> logins.items() # Both pieces together as tuples
[(‘justwhispers’, (‘jimmy’, ‘punk’)), (‘slashdot’, (‘juan’,
‘lemmein’)), (‘hotmail’, (‘jrf5’, ‘18thStreet’))]
>>> logins.clear() # Delete everything
>>> logins
{}
You can destructively iterate through a dictionary by calling its popitem() method,
which removes a random key and its value from the dictionary:
>>> d = {‘one’:1, ‘two’:2, ‘three’:3}
>>> try:
... while 1:
... print d.popitem()
... except KeyError: # Raises KeyError when empty
... pass
(‘one’, 1)
(‘three’, 3)
(‘two’, 2)
popitem是 2.1 版里的。
Dictionary 对象还提供了 copy() 方法,它创建某个 dictionary 的一个浅拷贝:
>>> a = {1:’one’, 2:’two’, 3:’three’}
>>> b = a.copy()
>>> b
{3: ‘three’, 2: ‘two’, 1: ‘one’}
相关推荐
- **Data Structures**: Understand how to work with lists, dictionaries, and tuples. - **Control Flow**: Learn about if-else statements, loops, and exception handling. 2. **Using Python in ArcGIS ...
Finding Unions and Intersections of Dictionaries Recipe 4.18. Collecting a Bunch of Named Items Recipe 4.19. Assigning and Testing with One Statement Recipe 4.20. Using printf in Python ...
Numerical values can be specified either with decimal (no prefix), octal (prefix '0') or hexadecimal (prefix '0x') base. Call 'ethercat <COMMAND> --help' for command-specific help. 以上内容为...
PEP 372: Ordered Dictionaries PEP 378: Format Specifier for Thousands Separator Other Language Changes New, Improved, and Deprecated Modules Optimizations IDLE Build and C API Changes Porting ...