欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

笨办法学Python3 习题39 字典

程序员文章站 2022-07-11 15:34:59
...

列表是一种数据结构, 同样字典也是,字典也是用来存储数据,但是要获得字典中的数据,不是通过索引了。字典也是最常用的一种数据结构。

习题39:

列表可以这样:可以通过数值来找到列表中的元素(也只能通过数值)

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

字典呢?字典可以通过任何东西找到元素。其实呢,字典可以将一样东西与另一样东西关联。这种东西不可以,但是关联的东西可以,那也可以啊!

>>> stuff = {'name':'shub','age':23,'height':170+5}
>>> print(stuff['name'])
shub
>>> print(stuff['age'])
23
>>> print(stuff['height'])
175
>>> stuff['city'] = "BoZhou"
>>> print(stuff['city'])
BoZhou

我们从上例中看到,除了通过数值,还可以通过字符串来从字典中获取stuff,我们还可以用字符串往字典中添加元素。


>>> stuff[1] = 'whoa'
>>> stuff[2] = 'wawa'
>>> print(stuff[1],stuff[2])
whoa wawa

​

只放多没意思,咱们还要能删除。

>>> del stuff['city']
>>> del stuff[1]
>>> stuff
{'name': 'shubo', 'age': 23, 'height': 175, 2: 'wawa'}
>>> del stuff[2]
>>> stuff
{'name': 'shubo', 'age': 23, 'height': 175}

字典的关键理念就是映射(或叫关联)

#习题39 字典,可爱的字典
# create a mapping of province to abbreviation
province = {
    'Anhui':'ah',
    'Hebei':'hb',
    'Jiangsu':'js',
    'Henan':'hn',
    'Shandong':'sd'
}

# create a basic set of province and some cities in them
cities = {
    'js':'NanJing',
    'sd':'Jinan',
    'hn':'Zhengzhou'
}

#Add some more cities
cities['hb'] = 'Shijiazhuang'
cities['ah'] = 'Hefei'

# print out some more cities
print('-' * 10)
print("hb province has:",cities['hb'])
print("ah province has:",cities['ah'])

# print some province
print('-' * 10)
print("Jiangsu's abbreviation is:",province['Jiangsu'])
print("Shandong's abbreviation is:",province['Shandong'])

# do it by using the province then cities dict              #通过使用省和城市词典来实现     
print('-' * 10)
print("Anhui has:",cities[province['Anhui']])
print("Hebei has:",cities[province['Hebei']])

# print every province abbreviation
print('-' * 10)
for pro, abbrev in list(province.items()):            #
    print(f"{pro} is abbreviated {abbrev}")

# print every city in province
print('-' * 10)
for abbrev,city in list(cities.items()):
    print(f"{abbrev} has the city {city}")

# now do both at the same time
print('-' * 10)
for pro,abbrev in list(province.items()):
    print(f"{pro} province is abbreviated {abbrev}")
    print(f"and has city {cities[abbrev]}")

print('-' * 10)
# safely get a abbreviation by province that might not be there
pro = province.get('Zhejiang')                         #get

if not pro:                                            #if not
    print("Sorry, no Zhejiang")

# get a city with a default value
city = cities.get('zj','Does not Exist')                    #与上个get用法不一样
print(f"The city for the province 'Zhejiang' is: {city}")

运行结果: 

hb province has: Shijiazhuang
ah province has: Hefei
----------
Jiangsu's abbreviation is: js
Shandong's abbreviation is: sd
----------
Anhui has: Hefei
Hebei has: Shijiazhuang
----------
Anhui is abbreviated ah
Hebei is abbreviated hb
Jiangsu is abbreviated js
Henan is abbreviated hn
Shandong is abbreviated sd
----------
js has the city NanJing
sd has the city Jinan
hn has the city Zhengzhou
hb has the city Shijiazhuang
ah has the city Hefei
----------
Anhui province is abbreviated ah
and has city Hefei
Hebei province is abbreviated hb
and has city Shijiazhuang
Jiangsu province is abbreviated js
and has city NanJing
Henan province is abbreviated hn
and has city Zhengzhou
Shandong province is abbreviated sd
and has city Jinan
----------
Sorry, no Zhejiang

Python 字典 get() 函数返回指定键的值,如果值不在字典中返回默认值。

dict.get(key, default=None)
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。
dict = {'Name': 'shub', 'Age': 23}

print ("Age 值为:",dict.get('Age'))
print ("Sex 值为:",dict.get('Sex', "no"))

结果:

Age 值为: 23
Sex 值为: no

列表和字典有何不同?列表是一些项的有序排列,而字典是将一些项(键)对象到另外一些项(值)的数据结构。

字典能用在哪里?各种需要通过一个值去查看另一个值得场合。

列表能用在哪里?列表是专供需要有序排列的数据使用的。只要知道索引就能查到对应的值了。

有没有办法弄到一个可以排序的字典?:

collections.OrderedDict

很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有个模块collections(英文,收集、集合),里面自带了一个子类OrderedDict,实现了对字典对象中元素的排序。