一 字典的理解
1 概念:字典(也叫 dict)是一种和列表类似的数据存储方式。但是不同于列表只能用数字获取数据,字典可以用任何东西来获取。你可以把字典当成是一个存储和组织数据的数据库。
2 和列表的区别:
- 我们只能用数字来取出列表中的元素。
- 字典能让你用几乎所有的东西(字符串、数字,必须是可哈希的),而不只是数字。是的,字典能够把一个东西和另一个东西关联起来,不管它们是什么类型。
-
列表是元素的有序排列。而字典是把一些元素(称为“键”,keys)和另一些元素(称为“值”,values)匹配起来
- 我能用字典做什么? 当你需要用一个东西去查另一个东西的时候。其实,你可以把字典称为“查询表”(look up tables)。
- 我能用列表做什么? 可以用于任何有序排列的东西,同时你只需要用数字索引来查找它们
3 字典的其它内容见网址:https://www.cnblogs.com/luoxun/p/13356547.html
二 代码
ex39.py
1 # -*- coding:utf-8 -*- 2 3 # create a mapping of state to abbreviation 创建一个州名到缩写的映射 4 states = { 5 'Oregon':'OR', # 俄勒冈州 6 'Florida':'FL', # 佛罗里达州(美国) 7 'Califoria':'CA', # 加利福尼亚州 8 'New York':'NY', # 纽约 9 'Michigan':'MI' # 密歇根 10 } 11 12 # create a basic set of states and some cities in them 13 cities = { 14 'CA':'San Francisco', # 圣弗朗西斯科 15 'MI':'Detroit', # 底特律 16 'FL':'Jacksonville' # 杰克逊维尔 17 } 18 19 # add some more cities 20 cities['NY'] = 'New York' 21 cities['OR'] = 'Portland' # 波特兰 22 23 # printt some states 24 print('-' * 10) 25 print("Michigan's abbreviation is:", states['Michigan']) 26 print("Florida's abbreviation is:",states['Florida']) 27 28 # do it by using the state then cities dict 29 print('-'*10) 30 print("Michigan has:",cities[states['Michigan']]) 31 print("Florida has:",cities[states['Florida']]) 32 33 # print every city in state 34 print('-' * 10) 35 for abbrev,city in list(cities.items()): 36 print(f"{abbrev} has the city {city}") 37 38 # now do both at the same time 39 print('-' * 10) 40 for state,abbrev in list (states.items()): 41 print(f"{state} state is abbreviated {abbrev}") 42 print(f"and has city {cities[abbrev]}") 43 44 print('-' * 10) 45 # safely get a abbreviation by state that might not be there 46 state = states.get('Texas.') 47 48 if not state: 49 print("Sorry,no Texas.") 50 51 # get a city with a default value 52 city = cities.get('TX','Does Not Exit') 53 print(f"The city for the state 'TX' is: {city}")
运行结果
1 PS E:6_AI-Study1_Python2_code_python 2_LearnPythonTheHardWay> python ex39.py 2 ---------- 3 Michigan's abbreviation is: MI 4 Florida's abbreviation is: FL 5 ---------- 6 Michigan has: Detroit 7 Florida has: Jacksonville 8 ---------- 9 CA has the city San Francisco 10 MI has the city Detroit 11 FL has the city Jacksonville 12 NY has the city New York 13 OR has the city Portland 14 ---------- 15 Oregon state is abbreviated OR 16 and has city Portland 17 Florida state is abbreviated FL 18 and has city Jacksonville 19 Califoria state is abbreviated CA 20 and has city San Francisco 21 New York state is abbreviated NY 22 and has city New York 23 Michigan state is abbreviated MI 24 and has city Detroit 25 ---------- 26 Sorry,no Texas. 27 The city for the state 'TX' is: Does Not Exit