1 dictionary
1.1 Mutable and immutable types
- Sequences are indexed by consecutive integers. The difference is that dictionaries are indexed by "keywords". Keywords can be of any immutable type, usually strings or numbers.
- Python is only a dictionary mapping type , a string, a tuple list belongs sequence type .
So how quickly determine a data typeX
is not the type of variable it? Two methods: - Trouble Method: The
id(X)
function of X for a certain operation, comparing before and after the operationid
, if not the same, itX
can not be changed, if the same, isX
variable. - Convenient methods: using
hash(X)
, as long as no error, proofX
can be hashed, i.e. can not be changed, can not be hashed in turn, can change.
【example】
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
- Integer
i
in Canada after aid
different man before, so this after the completion of the additioni
(although the name is not changed), but not before adding thati
, so integers are immutable. - A list of
l
additional'Python'
afterid
and before the same, so the list is variable types.
【example】
print(hash('Name')) # -9215951442099718823
print(hash((1, 2, 'Python'))) # 823362308207799471
print(hash([1, 2, 'Python']))
# TypeError: unhashable type: 'list'
print(hash({
1, 2, 3}))
# TypeError: unhashable type: 'set'
- Values, characters, and tuples can all be hashed, so they are immutable types.
- Lists, sets, and dictionaries cannot be hashed, so they are mutable types.
1.2 Dictionary definition
A dictionary is an unordered set of key:value ( key:value
) pairs. The keys must be different from each other (within the same dictionary).
dict
Order and the internal storage ofkey
the order placed is not related.dict
Find and insert fast, not withkey
the increases, but it would take a lot of memory.
The dictionary definition syntax is{元素1, 元素2, ..., 元素n}
- Each element is a ``key-value pair'' - key: value (
key:value
) - The key points are "curly brackets ()", "comma," and "colon:"
- Braces-tie all elements together
- Comma-separate each key-value pair
- Colon-separate key and value
1.3 Create and access dictionaries
【example】
brand = ['李宁', '耐克', '阿迪达斯']
slogan = ['一切皆有可能', 'Just do it', 'Impossible is nothing']
print('耐克的口号是:', slogan[brand.index('耐克')])
# 耐克的口号是: Just do it
dic = {
'李宁': '一切皆有可能', '耐克': 'Just do it', '阿迪达斯': 'Impossible is nothing'}
print('耐克的口号是:', dic['耐克'])
# 耐克的口号是: Just do it
key
Create a dictionary by string or numeric value .
Note: If the key we take does not exist in the dictionary, an error will be reported directly KeyError
.
【example】
dic1 = {
1: 'one', 2: 'two', 3: 'three'}
print(dic1) # {1: 'one', 2: 'two', 3: 'three'}
print(dic1[1]) # one
print(dic1[4]) # KeyError: 4
dic2 = {
'rice': 35, 'wheat': 101, 'corn': 67}
print(dic2) # {'wheat': 101, 'corn': 67, 'rice': 35}
print(dic2['rice']) # 35
[Example] Use tuples key
to create a dictionary, but it is generally not used in this way.
dic = {
(1, 2, 3): "Tom", "Age": 12, 3: [3, 5, 7]}
print(dic) # {(1, 2, 3): 'Tom', 'Age': 12, 3: [3, 5, 7]}
print(type(dic)) # <class 'dict'>
dict
Create a dictionary through the constructor .
dict()
-> Create an empty dictionary.
[Example] Bykey
directly putting the data into the dictionary, but onekey
can only correspond to onevalue
, andkey
putting into one multiple timesvalue
, the latter value will wash out the previous value.
dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print(dic)
# {'a': 1, 'b': 2, 'c': 3}
dic['a'] = 11
print(dic)
# {'a': 11, 'b': 2, 'c': 3}
dic['d'] = 4
print(dic)
# {'a': 11, 'b': 2, 'c': 3, 'd': 4}
dict(mapping)
-> new dictionary initialized from a mapping object’s (key, value) pairs
【例子】
dic1 = dict([('apple', 4139), ('peach', 4127), ('cherry', 4098)])
print(dic1) # {'cherry': 4098, 'apple': 4139, 'peach': 4127}
dic2 = dict((('apple', 4139), ('peach', 4127), ('cherry', 4098)))
print(dic2) # {'peach': 4127, 'cherry': 4098, 'apple': 4139}
dict(**kwargs)
-> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
[Example] In this case, the key can only be a string type, and when it is created Strings cannot be quoted, and syntax errors will be reported directly if they are added.
dic = dict(name='Tom', age=10)
print(dic) # {'name': 'Tom', 'age': 10}
print(type(dic)) # <class 'dict'>
## 1.4 字典的内置方法
- `dict.fromkeys(seq[, value])` 用于创建一个新字典,以序列 `seq` 中元素做字典的键,`value` 为字典所有键对应的初始值。
【例子】
```python
seq = ('name', 'age', 'sex')
dic1 = dict.fromkeys(seq)
print("新的字典为 : %s" % str(dic1))
# 新的字典为 : {'name': None, 'age': None, 'sex': None}
dic2 = dict.fromkeys(seq, 10)
print("新的字典为 : %s" % str(dic2))
# 新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
dic3 = dict.fromkeys(seq, ('小马', '8', '男'))
print("新的字典为 : %s" % str(dic3))
# 新的字典为 : {'name': ('小马', '8', '男'), 'age': ('小马', '8', '男'), 'sex': ('小马', '8', '男')}
dict.keys()
Returns an iterator object that can be usedlist()
to convert to the list, a list of all keys in the dictionary.
【example】
dic = {
'Name': 'lsgogroup', 'Age': 7}
print(dic.keys()) # dict_keys(['Name', 'Age'])
lst = list(dic.keys()) # 转换为列表
print(lst) # ['Name', 'Age']
dict.values()
Returns an iterator can be usedlist()
to convert a list, a list of all the values of the dictionary.
【example】
dic = {
'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print("字典所有值为 : ", list(dic.values()))
# 字典所有值为 : [7, 'female', 'Zara']
dict.items()
Return a traversable (key, value) tuple array as a list.
【example】
dic = {
'Name': 'Lsgogroup', 'Age': 7}
print("Value : %s" % dic.items())
# Value : dict_items([('Name', 'Lsgogroup'), ('Age', 7)])
print(tuple(dic.items()))
# (('Name', 'Lsgogroup'), ('Age', 7))
dict.get(key, default=None)
Return the value of the specified key, or the default value if the value is not in the dictionary.
【example】
dic = {
'Name': 'Lsgogroup', 'Age': 27}
print("Age 值为 : %s" % dic.get('Age')) # Age 值为 : 27
print("Sex 值为 : %s" % dic.get('Sex', "NA")) # Sex 值为 : NA
dict.setdefault(key, default=None)
And aget()
method similar, if the key does not exist in the dictionary, it will add key and value to the default value.
【example】
dic = {
'Name': 'Lsgogroup', 'Age': 7}
print("Age 键的值为 : %s" % dic.setdefault('Age', None)) # Age 键的值为 : 7
print("Sex 键的值为 : %s" % dic.setdefault('Sex', None)) # Sex 键的值为 : None
print("新字典为:", dic)
# 新字典为: {'Age': 7, 'Name': 'Lsgogroup', 'Sex': None}
key in dict
in
The operator is used to determine whether the key exists in the dictionary, if the key is returned in the dictionary dicttrue
, otherwise it is returnedfalse
. Thenot in
operator is just the opposite, if the key is returned in the dictfalse
, otherwise it is returnedtrue
.
【example】
dic = {
'Name': 'Lsgogroup', 'Age': 7}
# in 检测键 Age 是否存在
if 'Age' in dic:
print("键 Age 存在")
else:
print("键 Age 不存在")
# 检测键 Sex 是否存在
if 'Sex' in dic:
print("键 Sex 存在")
else:
print("键 Sex 不存在")
# not in 检测键 Age 是否存在
if 'Age' not in dic:
print("键 Age 不存在")
else:
print("键 Age 存在")
# 键 Age 存在
# 键 Sex 不存在
# 键 Age 存在
dict.pop(key[,default])
Remove dictionary given keykey
value corresponding to the return value is deleted.key
The value must be given. Ifkey
not present, then the returndefault
value.del dict[key]
Delete dictionary given keykey
value corresponds.
【example】
dic1 = {
1: "a", 2: [1, 2]}
print(dic1.pop(1), dic1) # a {2: [1, 2]}
# 设置默认值,必须添加,否则报错
print(dic1.pop(3, "nokey"), dic1) # nokey {2: [1, 2]}
del dic1[2]
print(dic1) # {}
dict.popitem()
Randomly return and delete a pair of keys and values in the dictionary. If the dictionary is already empty but this method is called, a KeyError exception will be reported.
【example】
dic1 = {
1: "a", 2: [1, 2]}
print(dic1.popitem()) # (1, 'a')
print(dic1) # {2: [1, 2]}
dict.clear()
Used to delete all elements in the dictionary.
【example】
dic = {
'Name': 'Zara', 'Age': 7}
print("字典长度 : %d" % len(dic)) # 字典长度 : 2
dict.clear()
print("字典删除后长度 : %d" % len(dic)) # 字典删除后长度 : 0
dict.copy()
Return a shallow copy of the dictionary.
【example】
dic1 = {
'Name': 'Lsgogroup', 'Age': 7, 'Class': 'First'}
dic2 = dic1.copy()
print("新复制的字典为 : ", dic2)
# 新复制的字典为 : {'Age': 7, 'Name': 'Lsgogroup', 'Class': 'First'}
[Example] The difference between direct assignment and copy
dic1 = {
'user': 'lsgogroup', 'num': [1, 2, 3]}
# 引用对象
dic2 = dic1
# 深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dic3 = dic1.copy()
print(id(dic1)) # 148635574728
print(id(dic2)) # 148635574728
print(id(dic3)) # 148635574344
# 修改 data 数据
dic1['user'] = 'root'
dic1['num'].remove(1)
# 输出结果
print(dic1) # {'user': 'root', 'num': [2, 3]}
print(dic2) # {'user': 'root', 'num': [2, 3]}
print(dic3) # {'user': 'runoob', 'num': [2, 3]}
dict.update(dict2)
The dictionary parameterdict2
ofkey:value
updates to the dictionarydict
in.
【example】
dic = {
'Name': 'Lsgogroup', 'Age': 7}
dic2 = {
'Sex': 'female', 'Age': 8}
dic.update(dic2)
print("更新字典 dict : ", dic)
# 更新字典 dict : {'Sex': 'female', 'Age': 8, 'Name': 'Lsgogroup'}