笨办法学python3 学习笔记 习题39 字典,可爱的字典

习题39 字典,可爱的字典

# 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 list(states.items()):
    print(f"{state} is abbreviation {abbrev}")

# print every city in state
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 state,abbrev in list(states.items()):
    print(f"{state} state is abbreviation {abbrev}")
    print(f"and has city {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(f"The city for the state 'TX' is: {city}")
----------
NY State has: New York
OR State has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviation OR
Florida is abbreviation FL
California is abbreviation CA
New York is abbreviation NY
Michigan is abbreviation 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 abbreviation OR
and has city Portland
Florida state is abbreviation FL
and has city Jacksonville
California state is abbreviation CA
and has city San Francisco
New York state is abbreviation NY
and has city New York
Michigan state is abbreviation MI
and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does Not Exist

字典(Dictionary)

  • 字典是另一种可变容器模型,且可存储任意类型对象。

  • 字典是可变的

  • 字典是包括在{}中,含有key(键):value(值)格式的键值对,且每个键值对之间用,分割的模型

    格式如下所示:

    d = {key1 : value1, key2 : value2 }

  • 键一般是唯一的,值不需要唯一。

    如果键重复,最后的一个键值对会替换前面的

  • 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。列表不行。

创建字典

  1. 方法一:花括号括住键值对

    ​ {‘键’:‘值’, … ,‘键’:‘值’ }

  2. 方法二:dict()函数

    ​ dict(键=值,键=值)

实例
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }

访问字典里的值

  • 返回所有键

    字典名. key()

  • 返回所有值

    字典名.value()

  • 返回键值对的元组

    字典名.items()

  • 返回键对应的值

    字典名.get()

把相应的键放入字典名称后的方括弧,如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
dict['Name']:  Zara
dict['Age']:  7

如果用字典里没有的键访问数据,会输出错误如下:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Alice']: ", dict['Alice']
dict['Alice']: 
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print "dict['Alice']: ", dict['Alice']
KeyError: 'Alice'

修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对。如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加


print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
dict['Age']:  8
dict['School']:  RUNOOB

删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

  • 删除键对应的键值对

    dict.pop() # 返回删除的键值对

    del dict[‘键’]

  • 删除字典

    del dict

  • 清空字典中的内容

    dict.clear()

如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name']  # 删除键是'Name'的条目
dict.clear()      # 清空字典所有条目
del dict          # 删除字典

print "dict['Age']: ", dict['Age'] 
print "dict['School']: ", dict['School']

但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'] 
TypeError: 'type' object is unsubscriptable

注:del()方法后面也会讨论。

键的特性

字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。

两个重要的点需要记住:

  1. 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
  2. 键必须不可变,所以可以用数字,字符串或元组充当,用列表就不行

字典内置函数&方法

Python字典包含了以下内置函数:

序号函数及描述
len(dict)计算字典元素个数,即键的总数
str(dict)输出字典,以可打印的字符串表示
type(variable)返回输入的变量类型,如果变量是字典就返回字典类型

Python字典包含了以下内置方法:

序号函数及描述
dict.clear()删除字典内所有元素
dict.copy()返回一个字典的浅复制
dict.fromkeys(seq[, val])创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
dict.get(key, default=None)返回指定键的值,如果值不在字典中返回default值
key in dict如果键在字典dict里返回true,否则返回false
dict .items()以列表返回可遍历的(键, 值) 元组数组
dict.keys()返回一个迭代器,可以使用 list() 来转换为列表
dict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
dict.update(dict2)把字典dict2的键/值对更新到dict里
dict.values()以列表返回字典中的所有值
pop(key[,default])删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值
popitem()返回并删除字典中的最后一对键和值

.items()方法

字典(Dictionary)

描述

Python 字典(Dictionary) items() 函数把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回

语法

dict.items()

参数

  • NA。

返回值

返回可遍历的(键, 值) 元组数组。

.get()方法

字典(Dictionary)

描述

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

语法

dict.get(key, default=None)

参数

  • key – 字典中要查找的键。
  • default – 如果指定键的值不存在时,返回该默认值。

返回值

返回指定键的值,如果值不在字典中返回默认值None。

实例

dict = {'Name': 'Runoob', 'Age': 27}

**print** "Value : %s" %  dict.get('Age')
**print** "Value : %s" %  dict.get('Sex', "Never")
Value : 27
Value : Never

dick. keys() 方法

描述

dick.keys() 方法返回一个可迭代对象,可以使用 list() 来转换为列表。

语法

dict.keys()

参数

  • NA。

返回值

返回一个迭代器。

实例

以下实例展示了 keys() 方法的使用方法:

>>> dict = {'Name': 'Runoob', 'Age': 7}
>>> dict.keys()
dict_keys(['Name', 'Age'])
>>> list(dict.keys())             # 转换为列表
['Name', 'Age']
>>> 

以上实例输出结果为:

字典所有的键为 : dict_keys(['Age', 'Name'])
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值