笨办法39字典dict

时间:2023-04-04 18:15:32

一开始没看明白,直接把句子缩短了,输出结果看字典的用法

 stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
stuff['city'] = "San Francisco"
stuff[1] = "Wow"
stuff[2] = "Neato"
print(stuff)

运行了3次,输出不同结果,就贴两个吧。。

笨办法39字典dict

笨办法39字典dict

运行结果,键及对应值的顺序都不同。

字典中的值并没有特殊的顺序,但都存储在一个特定的键(Key)里。键可以是数字、字符串甚至是元组。(python基础教程p55)

以下原文代码:

 # create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
} # create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
} # add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland' # print out some cities
print('-' * 10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR']) # print some states
print('-' * 10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida']) # do it by using the state then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']]) # print every state abbreviation
print('-' * 10)
for state, abbrev in states.items():
print("%s is abbreviated %s" % (state, abbrev)) # print every city in state
print('-' * 10)
for abbrev, city in cities.items():
print("%s has the city %s" % (abbrev, city)) # now do both at the same time
print('-' * 10)
for 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 there
state = states.get('Texas') if not state:
print("Sorry, no Texas.") # get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print("The city for the state 'TX' is: %s" % city)

基本字典操作:

k in d(d为字典)检查d中是否有含有键为k的项,查找的是键,而不是值(判断是否存在)

a.items:将字典项以列表方式返回,返回时没有特殊顺序(键+值)

a.get(key,default):访问字典中不存在的项时,输出default,存在时,输出对应值