exercise 39 字典

来源:互联网 发布:淘宝卖家退款多久到账 编辑:程序博客网 时间:2024/06/06 12:26

简单介绍:

list的使用:

>>> things = ['a', 'b', 'c', 'd']
>>> print things[1]
b
>>> things[1] = 'z'
>>> print things[1]
z
>>> things
['a', 'z', 'c', 'd']


dictionary的使用:

>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2} #列表使用方括号[  ] 字典使用大括号{ }
>>> print stuff['name']
Zed
>>> print stuff['age']
39
>>> print stuff['height']
74
>>> stuff['city'] = "San Francisco"
>>> print stuff['city']
San Francisco


使用一个字符串为字典插入数据:
>>> stuff[1] = "Wow"
>>> stuff[2] = "Neato"
>>> print stuff[1]
Wow
>>> print stuff[2]
Neato
>>> print stuff
{'city': 'san Francisco', 2: 'Neato', 'name': 'Zed', 1: 'Wow', 'age': 36, 'height': 74}   #为什么插入位置是这个鬼样子呢??


删除数据:
>>> del stuff['city']
>>> del stuff[1]
>>> del stuff[2]
>>> stuff
{'name': 'Zed', 'age': 36, 'height': 74}
>>> 


练习:

# create a mapping of state to abbreviationstates= {    "Oregon": "OR",    "Florida": "FL",    "California": "CA",    "New York": "NY",    "Michigan": "MI"}# create a basic set of states and some cities in themcities = {    'CA': 'San Francisco',    'MI': 'Detroit',    'FL': 'Jacksonville'}# add some more citiescities['NY'] = 'New York'cities['OR'] = 'Portland'# print out some citiesprint '-' * 10print "NY State has: ", cities['NY']print "OR State has: ", cities['OR']# print some statesprint '-' * 10print "Michigan's abbreviation is: ", states['Michigan']print "Florida's abbreviation is: ", states['Florida']# do it by using the state then cities dictprint '-' * 10print "Michigan has: ", cities[states['Michigan']]print "Florida has: ", cities[states['Florida']]# print every state abbreviationprint '-' * 10for state, abbrev in states.items():       print "%s is abbreviated %s" % (state, abbrev)# print every city in stateprint '-' * 10for abbrev, city in cities.items():    #Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。    print "%s has the city %s" % (abbrev, city)# now do both at the same timeprint '-' * 10for state, abbrev in states.items()
    print "%s state is abbreviated %s and has city %s" % (        state, abbrev, cities[abbrev])print '-' * 10# safely get a abbreviation by state that might not be therestate = states.get('Texas')            # dict.get(key, default=None)  总结中有例子if not state:    print "Sorry, no Texas."# get a city with a default valuecity = cities.get('TX', 'Does Not Exist')print "The city for the state 'TX' is: %s" % city



编程细节:

1、字典用大括号,每个数据之间用逗号隔开,最后一个不用逗号

2、加入新数据的时候 如下格式;用方括号里面的内容作为索引。

cities['NY'] = 'New York'

3、

print 'NY state has: ' , cities['NY']  ##中间有逗号!!! 前面没有%x的符号,后面不需要加%

4、

5、


总结:

1.获取字典值有两种方法,一个是通过dict['key'],  另一个是dict.get()方法。

dict.get(key,default=None)

eg:

>>> info ={'1':'first','2':'second','3':'third'}
>>> number =raw_input('input type you number:')
input type you number:3
>>> printinfo.get(number,'error')
third
>>> number =raw_input('input type you number:')
input type you number:4
>>> printinfo.get(number,'error')
error


2. dict.items()用法:

Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

eg:

dict = {'Name': 'Zara', 'Age': 7}print "Value : %s" %  dict.items()

输出:

Value : [('Age', 7), ('Name', 'Zara')]   # reverse order when output


Study Drill:

列表和字典的区别:

列表长用于已经排好顺序的元素中,字典是为了匹配关键字和数值

A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called "keys") to other items (called "values").


3.collections.OrderedDict

OrderedDict 有序字典

OrderedDict是dict的子类,它记住了内容添加的顺序。
比较时,OrderedDict要内容和顺序完全相同才会视为相等










 













0 0