第一章 数据结构 -- 字典

第零章 学前准备
第一章 数据结构 – 基本数据类型
第一章 数据结构 – 字符串
第一章 数据结构 – 列表、元组和切片
第一章 数据结构 – 字典


第一章 数据结构 – 字典

1.2 组合数据类型

1.2.5 字典

​字典由键和值组成,其中键必须是可散列对象。

1.2.5.1 定义字典
# 1、常用方式
a = dict(one=1, two=2, three=3)
b = {
    
    'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({
    
    'three': 3, 'one': 1, 'two': 2})
print(a == b == c == d == e)
# 2、字典推导(dictcomp)
DIAL_CODES = [(86, 'China'), (91, 'India'), (1, 'United States'), (62, 'Indonesia'), (55, 'Brazil'),
              (92, 'Pakistan'), (880, 'Bangladesh'), (234, 'Nigeria'), (7, 'Russia'), (81, 'Japan'), ]
country_code = {
    
    country: code for code, country in DIAL_CODES}
print(country_code)
{
    
    code: country.upper() for country, code in country_code.items() if code < 66}
1.2.5.2 常见映射方法
import traceback
test_dict = {
    
    }
# 1", "赋值
test_dict['name'] = "nfc"
# 2", "取值
# 2.1 使用[]取值,当建不存在时,会抛出KeyError异常
print(test_dict["name"])
try:
    print(test_dict["age"])
except Exception as e:
    traceback.print_exc()
# 2.2 使用get取值
print(test_dict.get("age", 18))
# 3", "设置默认值setdefault,也可以解决由键不存在引发的KeyError
test_dict.setdefault("company", "honor")
print(test_dict["company"])
# 4", "更新字典,没有添加,有则改之
test_dict.update({
    
    "name": "Nfc", "position": "Testing Engineer"})
print(test_dict)
# 5", "获取所有键
print(test_dict.keys())
# 6", "获取所有值
print(test_dict.values())
# 7", "获取所有键值对
print(test_dict.items())
# 9", "返回对应键的值,并删除这个键值对:pop
print(test_dict.pop("position"))
print(test_dict)
# 10", "随机返回一个键值对,并删除它:popitem
print(test_dict.popitem())
print(test_dict)
# 11", "clear
test_dict.clear()
print(test_dict)
1.2.5.3 处理找不到键时
1.2.5.3.1 使用 getsetdefault

当字典 d[k] 不能找到正确的键的时候, Python 会抛出异常,这个行为符合 Python 所信奉的“快速失败”哲学。也许每个 Python 程序员都知道可以用 d.get(k, default) 来代替 d[k] ,给找不到的键一个默认的返回值(这比处理 KeyError 要方便不少)。也可以使用 setdefault

char_string = "abdsaeiydhfwhrwjkqejsjfhwhegwrh"
counter = {
    
    }
for char in char_string:
    counter[char] = counter.get(char, 0) + 1
print(counter)
counter.clear()
for char in char_string:
    counter[char] = counter.setdefault(char, 0) + 1
print(counter)
{'a': 2, 'b': 1, 'd': 2, 's': 2, 'e': 3, 'i': 1, 'y': 1, 'h': 5, 'f': 2, 'w': 4, 'r': 2, 'j': 3, 'k': 1, 'q': 1, 'g': 1}
{'a': 2, 'b': 1, 'd': 2, 's': 2, 'e': 3, 'i': 1, 'y': 1, 'h': 5, 'f': 2, 'w': 4, 'r': 2, 'j': 3, 'k': 1, 'q': 1, 'g': 1}
1.2.5.3.2 使用defaultdict

使用defaultdict需要可调用对象(Callable)提供初始值

import collections
# 把int构造方法作为default_factory来创建一个defaultdict。
# 如果counter并没有char的记录,那么default_factory会被调用,为查询不到的键创造一个值
counter = collections.defaultdict(int)
char_string="asadfsagsfasasaasasa"
for char in char_string:
    counter[char] = counter[char] + 1
print(counter)
defaultdict(<class 'int'>, {'a': 9, 's': 7, 'd': 1, 'f': 2, 'g': 1})
1.2.5.3.3 特殊方法__missing__

所有的映射类型在处理找不到的键的时候,都会牵扯到 __missing__ 方法。虽然基类 dict 并没有定义这个方法,但是 dict 是知道有这么个东西存在的。也就是说,如果有一个类继承了 dict ,然后这个继承类提供了 __missing__ 方法,那么在 __getitem__[] 碰到找不到的键的时候, Python 就会自动调用它,而不是抛出一个 KeyError 异常。

from collections import UserDict


class MyCounter(UserDict):
    def __missing__(self, key):
        return 0

char_string="asadfsagsfasasaasasa"
counter = MyCounter()
for char in char_string:
    counter[char] = counter[char] + 1
print(counter)
{'a': 9, 's': 7, 'd': 1, 'f': 2, 'g': 1}

猜你喜欢

转载自blog.csdn.net/qq_31654025/article/details/132800747