字典也是一种数据结构,是一种类似列表的一种存储数据的方法,但是获取其中的数据,并不是列表那样的数值索引,而是任何一个你想用的东西。这样你就可以把字典当作数据库来存储和组织数据了。
我们可以比较一下字典和列表的功能。
我们可以并且只能通过数值找到列表中的元素!!!!!!
而字典要做的是,让你可以通过任何东西(不止是数值)找到元素,它可以将一样东西和另外一样东西关联,不管它的类型是什么。
除了数值,还可以通过字符串从字典中获取stuff,还可以用字符串往字典中添加元素,而且还不止只有字符串:
除了添加东西到字典里没意思,还可以删除:
字典的例子
我就不截图了,代码供大家复制粘贴
字典的关键原理就是映射(或关联)
states={
'Orange': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
cities={
'CA':'SAN Fracisco',
'MI':'Detroit',
'FL':'Jacksonvile'
}
cities['NY']='New York'
cities['OR']='Portland'
print('-' *10)
print("NY State has: ", cities['NY'])
print("OR State has: ", cities['OR'])
print('-' *10)
print("Michigan's abbreviation is: ", states['Michigan'])
print("Florida's abbreviation is: ", states['Florida'])
print('-'*10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']])
print('-' *10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated {abbrev}")
print('-' *10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}")
print('-' *10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
print('-' *10)
state = states.get('Texas')
if not state:
print("Sorry, no Texas.")
city = cities.get('TX', 'Does Not Exist')
print(f"The city for the state 'TX' is: {city}")
- 字典和列表的不同:列表是有序排列,而字典是将一些项对应到另外一些项的数据结构。
- 字典的使用范围:各种需要通过某一个值取查看另一个值的场合。
- 列表的使用范围:专供需要有序排列的数据使用