PYTHON学习第N天

  1. 字典

序列是以连续的整数为索引,与此不同的是,字典以"关键字"为索引,关键字可以是任意不可变类型,通常用字符串或数值。
字典是 Python 唯一的一个 映射类型,字符串、元组、列表属于序列类型。
那么如何快速判断一个数据类型 X 是不是可变类型的呢?两种方法:

麻烦方法:用 id(X) 函数,对 X 进行某种操作,比较操作前后的 id,如果不一样,则 X 不可变,如果一样,则 X 可变。
便捷方法:用 hash(X),只要不报错,证明 X 可被哈希,即不可变,反过来不可被哈希,即可变。

i = 1
print(id(i))  # 140732167000896
i = i + 2
print(id(i))  # 140732167000960

l = [1, 2]
print(id(l))  # 4300825160
l.append('Python')
print(id(l))  # 4300825160

整数 i 在加 1 之后的 id 和之前不一样,因此加完之后的这个 i (虽然名字没变),但是不是加前的那个 i 了,因此整数是不可更改的。
列表 l 在附加 ‘Python’ 之后的 id 和之前一样,因此列表是可更改的。

print(hash('Name'))  # -9215951442099718823

print(hash((1, 2, 'Python')))  # 823362308207799471

print(hash([1, 2, 'Python']))
# TypeError: unhashable type: 'list'
print(hash('Name'))  # -9215951442099718823

print(hash((1, 2, 'Python')))  # 823362308207799471

print(hash([1, 2, 'Python']))
# TypeError: unhashable type: 'list'

字符和元组 都能被哈希,因此它们是不可更改的。列表不能被哈希,因此它是可更改的。

「字典」定义语法为 {元素1, 元素2, …, 元素n}

其中每一个元素是一个「键值对」- 键:值 (key:value)
关键点是「大括号 {}」,「逗号 ,」和「冒号 :」
大括号 把所有元素绑在一起
逗号 将每个键值对一一分开
冒号 将键和值分开

创建和访问字典

字典是无序的 键:值对(key:value 对)集合,键必须是互不相同的(在同一个字典之内)。

brand = ['李宁', '耐克', '阿迪达斯']
slogan = ['一切皆有可能', 'Just do it', 'Impossible is nothing']
print('耐克的口号是:', slogan[brand.index('耐克')])  
# 耐克的口号是: Just do it

dict1 = {'李宁': '一切皆有可能', '耐克': 'Just do it', '阿迪达斯': 'Impossible is nothing'}
print('耐克的口号是:', dict1['耐克'])  
# 耐克的口号是: Just do it

dict2 = {1: 'one', 2: 'two', 3: 'three'}
print(dict2)  # {1: 'one', 2: 'two', 3: 'three'}
print(dict2[1])  # one

dict3 = {'rice': 35, 'wheat': 101, 'corn': 67}
print(dict3)  # {'wheat': 101, 'corn': 67, 'rice': 35}
print(dict3['rice'])  # 35

dict(object) 函数用于创建一个字典。
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object’s (key, value) pairs从映射对象的(键,值)对初始化的新字典
dict(iterable) -> new dictionary initialized as if via:新字典的初始化方式如下:

d = {}
for k, v in iterable:
    d[k] = v

dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)

dict4 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dict4)  # {'cherry': 4098, 'apple': 4139, 'peach': 4127}

dict4 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dict4)  # {'peach': 4127, 'cherry': 4098, 'apple': 4139}

dict 内部存放的顺序和 key 放入的顺序是没有关系的。
dict 查找和插入的速度极快,不会随着 key 的增加而增加,但是需要占用大量的内存。
把数据放入 dict 还可以直接通过 key 放入。
一个 key 只能对应一个 value,多次对一个 key 放入 value,后面的值会把前面的值冲掉。

dict5 = dict(a=1, b=2, c=3)
print(dict5)  
# {'b': 2, 'a': 1, 'c': 3}

dict5['a'] = 11
print(dict5)  
# {'b': 2, 'a': 11, 'c': 3}

dict5['d'] = 4
print(dict5)  
# {'d': 4, 'c': 3, 'a': 11, 'b': 2}

参考文献

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值