python basis 5- dictionary

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/EngineerHe/article/details/100063614

python basis 5- dictionary

Here Insert Picture Description

type of data

dictionary

The dictionary definition, creation

Dictionary is a variable container type, and may store any type of object. The biggest difference is a dictionary and a list of "key-value pair", key correspondence with the value, stored in the dictionary order is not important, important is the "key" and "value" of the correspondence between dictionaries emphasized. In the dictionary, the key requirement is unique and immutable. So Dictionary features the following:

  • Find Fast
  • Sequence no key-value pair sequence
  • non-variable and unique key button

Create dictionary, use {}, with each key-value pairs :are separated by between each pair of ,split. As well as the use of dict and using methods fromkeys

>>> d1 = {'key':'value'}
# 使用dict()初始化字典,其中键必须是字符串
>>> d2 = dict(key='value')
# 使用dict创建时,下面的情况会出现bug
>>> key = 'name'
>>> d3 = dict(key='value')
# 这个代码,原本我们是想输出{'name':'value'},可以结果并不一样,所以使用dict初始化的时候需要注意
>>> print(d3)
{'key': 'value'}
# 使用fromkeys方法初始化字典
#初始化
>>> d4 = {}.fromkeys(['key1', 'key2'])
>>> d4
{'key1': None, 'key2': None}
>>> d5 = dict().fromkeys(['key1','key2'])
>>> d5
{'key1': None, 'key2': None}
# 初始化并赋值
>>> d6 = {}.fromkeys(['key1', 'key2'], 'value')
>>> d6
{'key1': 'value', 'key2': 'value'}
# 也可以先初始化,然后动态地添加
>> d7 = {}
>>> d7['key1'] = 'value1'
>>> d7['key2'] = 'value2'
>>> d7
{'key1': 'value1', 'key2': 'value2'}
# 使用zip函数把键列表和值列表打包成键值对一一对应的元组
>>> d8 = dict(zip(['key1', 'key2'], ['value1', 'value2']))
>>> d8
{'key1': 'value1', 'key2': 'value2'}
# 字典推导表达式
>>> d9 = {x:x**2 for x in [1,2,3]}
>>> d9
{1: 1, 2: 4, 3: 9}

Access, modify dictionary

And a list of dictionary, is a container for storing data; in the list may be accessed by a standard index of the next element, to access its corresponding value in a dictionary by a key, i.e., key: value; can be modified, added and other operations.

>>> d1 = {'type':'dict', 'code':'python'}
# 值访问
>>> d1['type']
'dict'
# 内容添加
>>> d1[1] = 2
>>> d1
{'type': 'dict', 'code': 'python', 1: 2}
# 内容修改
>>> d1['code'] = 'java'
>>> d1
{'type': 'dict', 'code': 'java', 1: 2}
# 删除元素,还可以是用del删除某个字典的key,或者删除整个字典;使用clear() 清空这个字典
>>> d1 = {'type':'dict', 'code':'python', 1:2}
>>> d1.pop('code') # d1的值为{'type': 'dict', 1: 2}
>>> del d1[1]      # d1的值为{'type': 'dict'}
>>> d1.clear()     # d1 = {}
>>> del d1
>>> print(d1)      # NameError: name 'd1' is not defined
# 如果有两个字典,可以使用update函数来更新其中某一个字典
# 从下面代码的结果上可以看出,如果d1中没有d2的元素,则添加进来;如果有,则修改为d2中的值
>>> d2 = {1:3,2:4,5:6}
>>> d1.update(d2)
>>> d1
{'type': 'dict', 1: 3, 2: 4, 5: 6}

Dictionary traversal

d = {'a':1, 'b':2, 'c':3}
# 遍历key值
for key in d:
    print("{} : {}".format(key, d[key]))
# 该方法和上面的方法是等价的
for key in d.keys():
    print("{} : {}".format(key, d[key]))
# 遍历value值
for value in d.values():
    print(value)
# 遍历字典项
for key_value in d.items():
    print(key_value)
# 遍历字典健值
for key,value in d.items():
    print("{} : {}".format(key, value))

Dictionary sort

There are two ways of ordering the dictionary, is a first list () function and dictionary keys () method of combining, list generated by sorting, and then output. The second method is to use the built-in function sorted () to sort, will return sorted keys.

# 使用list()函数,和keys()相结合
d = {1:2,7:8,3:4,5:6}
d_key = list(d.keys())
d_key.sort()
for key in d_key:
    print(key, d[key])
# 使用sorted函数
for key in sorted(d):
    print(key, d[key])

Determine whether there is key

In python2 judge a dictionary if you can use a key has_key and in two ways, but only in python3 methods exist,

>>> d = {'type': 'dict', 'code': 'java', 1: 2}
>>> 'code' in d
True
>>> 3 in d
False

Dictionary get () method

There is a case, we want to get one of the values of the dictionary, but not sure if it exists, if the direct write dict[key]is certainly not appropriate, then only the first interpretation, then the output. Is written, it is provided a method in python get(key, default=None), i.e. there is a direct output Ruoguo, if not present, the default value is output.

# 获取字典中的值
d = {'code':'python'}
if 'name' in d:
    print(d['name'])
else:
    print('default')
# get()替代 if ... else ...
print(d.get('name', 'default'))

Different dictionaries and lists

  • From the creation mode, using a list of square brackets, Dictionary using braces.
  • Dictionary object is disordered, as a mapping relationship represented by the key-value; elements in the list are ordered, may be obtained by a number of elements directly, or obtained by slicing a plurality of elements.
  • Relatively speaking, dictionary and more space-consuming because of the need to maintain key.
  • list as the number of normal growth in order to find the time complexity of elements is O (n), dict does not grow with the number of changes, all the time responsible for the O (1)

Guess you like

Origin blog.csdn.net/EngineerHe/article/details/100063614