dict(数据字典)

数据字典的创建可用以下几种方式:

dict()
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)

使用key-value参数创建字典。

>>> MLB_teams = dict(
...     Colorado="Rockies",
...     Chicago="White Sox",
...     Boston="Red Sox",
...     Minnesota="Twins",
...     Milwaukee="Brewers",
...     Seattle="Mariners",
... )

>>> MLB_teams
{
    'Colorado': 'Rockies',
    'Chicago': 'White Sox',
    'Boston': 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'Brewers',
    'Seattle': 'Mariners'
}

使用元组列表来创建字典。

>>> MLB_teams = dict(
...     [
...         ("Colorado", "Rockies"),
...         ("Chicago", "White Sox"),
...         ("Boston", "Red Sox"),
...         ("Minnesota", "Twins"),
...         ("Milwaukee", "Brewers"),
...         ("Seattle", "Mariners"),
...     ]
... )

>>> MLB_teams
{
    'Colorado': 'Rockies',
    'Chicago': 'White Sox',
    'Boston': 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'Brewers',
    'Seattle': 'Mariners'
}

使用zip函数返回的迭代器来创建字典。zip函数返回的迭代器中每一项得是一个二元组。

>>> places = [
...     "Colorado",
...     "Chicago",
...     "Boston",
...     "Minnesota",
...     "Milwaukee",
...     "Seattle",
... ]

>>> teams = [
...     "Rockies",
...     "White Sox",
...     "Red Sox",
...     "Twins",
...     "Brewers",
...     "Mariners",
... ]

>>> dict(zip(places, teams))
{
    'Colorado': 'Rockies',
    'Chicago': 'White Sox',
    'Boston': 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'Brewers',
    'Seattle': 'Mariners'
}

使用.fromkeys(iterable, value=None, /)函数创建value相同的字典。

>>> inventory = dict.fromkeys(["apple", "orange", "banana", "mango"], 0)

>>> inventory
{'apple': 0, 'orange': 0, 'banana': 0, 'mango': 0}

使用字典推导式来创建字典。

>>> squares = {integer: integer**2 for integer in range(1, 10)}
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

使用iterable或mapping,结合kwargs来创建字典。

MLB_teams = dict(
     [
         ("Colorado", "Rockies"),
         ("Chicago", "White Sox"),
     ]
    , a =1, b = 2
 )

print(MLB_teams)

MLB_teams2 = dict(
     zip(["Colorado", "Chicago"], ["Rockies", "White Sox"])
    , a =1, b = 2
 )

print(MLB_teams2)

输出结果:

{'Colorado': 'Rockies', 'Chicago': 'White Sox', 'a': 1, 'b': 2}
{'Colorado': 'Rockies', 'Chicago': 'White Sox', 'a': 1, 'b': 2}

下面是修改和更新数据字典的方法:
dict.get(key, default=None): 根据key,访问一个value。如果key不存在,则返回default参数指定的值。

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.get("apple")
100
>>> print(inventory.get("mango"))
None

dict.setdefault(key, default=None): 如果key存在,则不做修改,并返回所对应的value。若key不存在,则添加key,value键值对,使用default参数指定的值,并且方法返回default对应的值。

>>> inventory = {"apple": 100, "orange": 80}

>>> inventory.setdefault("apple")
100
>>> print(inventory.setdefault("mango"))
None
>>> inventory
{'apple': 100, 'orange': 80, 'mango': None}
>>> inventory.setdefault("banana", 0)
0
>>> inventory
{'apple': 100, 'orange': 80, 'mango': None, 'banana': 0}

dict.update(): 用于更新数据字典。此函数接收三种类型参数,数据字典,二元组的列表,kwargs参数。
下面示例为使用另一个数据字典更新当前数据字典。已存在的key被使用另一个字典的值更新,不存在的key-value直接添加到原字典中。

config = {
    "color": "green",
    "font": "Courier",
}

user_config = {
    "color": "red",
    "font": "Arial",
    "position": (200, 100),
}

config.update(user_config)

print(config)  # {'color': 'red', 'font': 'Arial', 'position': (200, 100)}

下面示例使用二元组列表做为参数。

config = {
    "color": "green",
    "font": "Courier",
}

config.update([("color", "red"), ("position", (200, 100))])

print(config) # {'color': 'red', 'font': 'Courier', 'position': (200, 100)}

下面示例使用kwargs参数来更新

config = {
    "color": "green",
    "font": "Courier",
}

config.update(color="yellow",position=(200, 100))

print(config) # {'color': 'yellow', 'font': 'Courier', 'position': (200, 100)}

dict.pop(key[, default]: 移除一个key,并返回其对应的value。如果key值不存在,则如果default传值了,就返回defaut值,否则报错。

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.pop("apple")
100
>>> inventory
{'orange': 80, 'banana': 100}

>>> inventory.pop("mango")
Traceback (most recent call last):
    ...
KeyError: 'mango'

>>> inventory.pop("mango", 0)
0

也可以直接使用del语句来移除一个key-value对,但就不会返回值了。

>>> del inventory["banana"]
>>> inventory
{'orange': 80}

dict.popitem(): 移除数据字典中的最后一个键值对 ,并以元组形式返回其(key, value)内容。

>>> inventory = {"apple": 100, "orange": 80, "banana": 100}

>>> inventory.popitem()
('banana', 100)
>>> inventory
{'apple': 100, 'orange': 80}

>>> inventory.popitem()
('orange', 80)
>>> inventory
{'apple': 100}

>>> inventory.popitem()
('apple', 100)
>>> inventory
{}

dict.clear(): 清空数据字典中的所有内容。

数据字典之间的运算符
==!=:尽管数据字典是有序的,但在判断是否相等时,是忽略其key的顺序的。

>>> [1, 2, 3] == [3, 2, 1]
False
>>> {1: 1, 2: 2, 3: 3} == {3: 3, 2: 2, 1: 1}
True

>>> [1, 2, 3] != [3, 2, 1]
True
>>> {1: 1, 2: 2, 3: 3} != {3: 3, 2: 2, 1: 1}
False

|, |=: 合并运算符。运算符右侧的内容会更新到左侧的字典中。这根本update方法效果一样。

default_config = {
    "color": "green",
    "width": 42,
}

user_config = {
    "path": "/home",
    "color": "red",
}

config = default_config | user_config
print(config)  # {'color': 'red', 'width': 42, 'path': '/home'}

下面使用|=运算符。

default_config = {
    "color": "green",
    "width": 42,
}

user_config = {
    "path": "/home",
    "color": "red",
}

default_config |= user_config
print(default_config)  # {'color': 'red', 'width': 42, 'path': '/home'}

Dictionary view objects: dict.keys(), dict.values(), dict.items() 都属于数据字典视图对象。它们有个特点,就是在迭代过程中不能改变其长度,但可以改变其内容。

dic = {'a': 1, 'b': 2, 'c':3}

for k, v in dic.items():
    # dic.pop(k)  RuntimeError: dictionary changed size during iteration
    # dic.popitem()  RuntimeError: dictionary changed size during iteration
    dic[k] = None  # 成功

print(dic)  # {'a': None, 'b': None, 'c': None}

字典的性能: 字典用下标(key)访问及修改元素的效率是很高的,时间复杂度为O(1)。因为字典中的key的hash值对应了内存的地址,这点与集合的存储方式相同。字典填加元素的性能也有集合类似。
成员检测 a in dict,或 a in dict.keys() 都是高效的, 但a in dict.values()则是低效的,因为需要遍历所有成员。

posted @ 2025-01-29 12:09  RolandHe  阅读(47)  评论(0)    收藏  举报