码迷,mamicode.com
首页 > 其他好文 > 详细

Dictionaries

时间:2014-07-14 23:26:50      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   os   2014   for   

A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. You can think of a dictionary as a mapping between a set of indices and a set of values. Each index, which is called a key, corresponds to a value. The association of a key and a value is called a key-value pair or sometimes an item.

As an example, we will build a dictionary that maps from English words to Spanish words, so the keys and values are all strings. The squiggly-brackets, {}, represent an empty dictionary. To add items to the dictionary, you can use square brackets.

 bubuko.com,布布扣                    

The key-value pairs are not in order, but that’s not a problem because the elements of a dictionary are never indexed with integer indices. Instead, you use the keys to look up the corresponding values:

 bubuko.com,布布扣

If the key isn’t in the dictionary, you get an exception. The len function works on dictionaries; it returns the number of key-value pairs.

The in operator works on dictionaries; it tells you whether something appears as a key in the dictionary (appearing as a value is not good enough).

 bubuko.com,布布扣

The in operator uses different algorithms for lists and dictionaries. For lists, it uses a search algorithm. As list gets longer, the search time gets longer in direct proportion. For dictionaries, Python uses an algorithm called hashtable that has a remarkable property: the in operator takes about the same amount of time no matter how many items there are in a dictionary.

 

from Thinking in Python

Dictionaries,布布扣,bubuko.com

Dictionaries

标签:style   blog   http   os   2014   for   

原文地址:http://www.cnblogs.com/ryansunyu/p/3842300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!