字典
字典是内置类型,无序的对象集合,字典是通过键来存取的,而不是通过偏移来存取。
字典基本操作
创建字典
In [1]: var = {"spam": 2, "eggs": 3}
In [2]: var
Out[2]: {'spam': 2, 'eggs': 3}
In [3]: var = dict(spam=2, eggs=3)
In [4]: var
Out[4]: {'spam': 2, 'eggs': 3}
In [5]: var = dict.fromkeys(["spam", "eggs"])
In [6]: var
Out[6]: {'spam': None, 'eggs': None}
字典中获取对象
字典获取值有两种方式,通过键来索引,或者使用 get(key, default=None)
方法来获取,使用 key
索引时,若 key
不存在字典中会抛出异常,而 get(key, default=None)
方法则会返回 None
或者设定值
In [1]: var = {"alex": 1, "seven": 2, "eric": 3}
In [2]: var["alex"] # 通过 key 索引
Out[2]: 1
In [3]: var.get("seven")
Out[3]: 2
添加/更新 字典对象
修改字典方式如下,当 key
不存在时则创建,当 key
存在时则更新
In [1]: var = {"alex": 1, "seven": 2, "eric": 3}
In [2]: var["tt"] = 4
In [3]: var
Out[3]: {'alex': 1, 'seven': 2, 'eric': 3, 'tt': 4}
In [4]: var["alex"] = 5
In [5]: var
Out[5]: {'alex': 5, 'seven': 2, 'eric': 3, 'tt': 4}
setdefault(key, default=None)
当字典中key
已经存在时返回键对应的value
,当key
不存在时则设置key
的值为default
In [6]: var.setdefault("alex", 8)
Out[6]: 5
In [7]: var
Out[7]: {'alex': 5, 'seven': 2, 'eric': 3, 'tt': 4}
update(e=None, **kwargs)
update
方法也可在字典中添加对象,还可合并两个字典
In [1]: a = {"alex": 1, "eric": 2, "seven": 3}
In [2]: b = {"c": 4}
In [3]: a.update(b)
In [4]: a
Out[4]: {'alex': 1, 'eric': 2, 'seven': 3, 'c': 4}
In [5]: a.update(d=5)
In [6]: a
Out[6]: {'alex': 1, 'eric': 2, 'seven': 3, 'c': 4, 'd': 5}
删除字典对象
pop(key)
返回指定键对应的值,并将它从字典中删除
In [1]: var = {"alex": 1, "seven": 2, "eric": 3}
In [2]: var.pop("alex")
Out[2]: 1
In [3]: var
Out[3]: {'seven': 2, 'eric': 3}
popitem()
随机返回并删除字典中一对键和值
In [1]: var = {"alex": 1, "seven": 2, "eric": 3}
In [2]: var.popitem()
Out[2]: ('eric', 3)
In [3]: var
Out[3]: {'alex': 1, 'seven': 2}
字典的迭代
迭代 key
值
In [1]: var = {"eric": 1, "alex": 2, "seven": 3}
In [2]: for key in var: # 字典默认迭代键值
...: print(var[key])
...:
1
2
3
keys()
In [1]: var = {"eric": 1, "alex": 2, "seven": 3}
In [2]: var.keys()
Out[2]: dict_keys(['eric', 'alex', 'seven'])
In [3]: for key in var.keys(): # 当迭代键值的时候建议使用上面的方法
...: print(key)
...:
eric
alex
seven
In [4]: list(var.keys())
Out[4]: ['eric', 'alex', 'seven']
迭代 value
值
values()
In [1]: var = {"eric": 1, "alex": 2, "seven": 3}
In [2]: var.values()
Out[2]: dict_values([1, 2, 3])
In [3]: for value in var.values():
...: print(value)
...:
1
2
3
In [4]: list(var.values())
Out[4]: [1, 2, 3]
迭代 key-value
键值对
items()
In [1]: var = {"eric": 1, "alex": 2, "seven": 3}
In [2]: var.items()
Out[2]: dict_items([('eric', 1), ('alex', 2), ('seven', 3)])
In [3]: list(var.items())
Out[3]: [('eric', 1), ('alex', 2), ('seven', 3)]
In [4]: for k, v in var.items():
...: print("key:", k, "value:", v)
...:
key: eric value: 1
key: alex value: 2
key: seven value: 3