b
z
['a','z','c','d']
Zed
3974
SF
Neato
Neato
{'name':'Zed','age':39,'height':74}
进程已结束,退出代码0
代码如下:
#create a mapping of state to above abbreviation
states={'Oregon':'OR','Florida':'FL','California':'CA','New York':'NY','Michigan':'MI'}print(states)#{}花括号是字典的标志#create a basic set of states and some cities in them
cities={'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville',}print(cities)#add some more cities
cities['NY']='New York'
cities['OR']='Portland'print(cities)#print out some citiesprint('-'*10)print("NY State has:",cities['NY'])print("OR State has:",cities['OR'])#do it by using the state then cities dictprint('-'*10)print("Michigan has:",cities[states['Michigan']])print("Florida has:",cities[states['Florida']])#print every state abbreviationprint('-'*10)for state,abbrev inlist(states.items()):print(f"{state} is abbreviated {abbrev}")#print every cities in stateprint('-'*10)for abbrev,city inlist(cities.items()):print(f"{abbrev} has the city {city}")#now do both at the same timeprint('-'*10)for state,abbrev inlist(states.items()):print(f"{state} state is abbreviated {abbrev}")print(f"and has city {cities[abbrev]}")print('-'*10)# safety get a abbreviation by state that might not be there
state=states.get('Texas')ifnot states:print("Sorry,no texas.")#get a city with a default value
city=cities.get('TX','Does Not Exist')print(f"The city for the state 'TX' is {city}")'''
列表和字典的不同:
列表是有序排列,字典是将{键}对应{值}
字典能用在哪里:
通过某个值查看另一个值,也可以把字典叫做“查找表”
列表能用在哪里:
专供有序排列的数据,只要知道索引就能查到对应的值了
排序的词典:
collections.OrderedDict
python中字典 Dict 是利用hash存储,各元素之间没有顺序 ;而在 OrderedDict 中是按照 添加顺序存储 的 有序 字典 ;
'''
结果输出:
{'Oregon':'OR','Florida':'FL','California':'CA','New York':'NY','Michigan':'MI'}{'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville'}{'CA':'San Francisco','MI':'Detroit','FL':'Jacksonville','NY':'New York','OR':'Portland'}----------
NY State has: New York
OR State has: Portland
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviated OR
Florida is abbreviated FL
California is abbreviated CA
New York is abbreviated NY
Michigan is abbreviated MI
----------
CA has the city San Francisco
MI has the city Detroit
FL has the city Jacksonville
NY has the city New York
OR has the city Portland
----------
Oregon state is abbreviated OR
and has city Portland
Florida state is abbreviated FL
and has city Jacksonville
California state is abbreviated CA
and has city San Francisco
New York state is abbreviated NY
and has city New York
Michigan state is abbreviated MI
and has city Detroit
----------
The city for the state 'TX'is Does Not Exist
进程已结束,退出代码0