首页 > 其他 > 详细

Dictionaries and tuples

时间:2014-07-19 23:02:26      阅读:480      评论:0      收藏:0      [点我收藏+]

Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair. As you should expect from a dictionary, the items are in no particular order. Conversely, you can use a list of tuples to initialize a new dictionary:

 bubuko.com,布布扣                      

Combining this feature with zip yields a concise way to create a dictionary:

 bubuko.com,布布扣

The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.

 bubuko.com,布布扣

Combining items, tuples assignment and for, you get the idiom for traversing the keys and values of a dictionary:

bubuko.com,布布扣 

It is common to use tuples as keys in dictionaries (primary because you can’t use lists). For examples, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:

directory[last,first] = number

The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary.

for last, first in directory:
          print first, last, directory[last,first]

This loop traverse the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number. There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple (‘Cleese’, ‘John’) would appear:

 bubuko.com,布布扣

But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear:

 bubuko.com,布布扣

Here the tuples are shown using Python syntax as a graphical shorthand.

 

from Thinking in Python

Dictionaries and tuples,布布扣,bubuko.com

Dictionaries and tuples

原文:http://www.cnblogs.com/ryansunyu/p/3855393.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!