python a basic data type (dictionary)

dictionary

List can store large amounts of data types, but only in the order of storage, correlation between data and data is not strong.

So we need to introduce a container-type data type, to solve the above problem, which requires dict dictionary.

Dictionary (dict) is the only ⼀ in the python ⼀ type mappings. He is enclosed in {} key-value pairs.

In the key is the only dict ⼀ In saved, ⼀ calculated memory address according to a key. The key-value is then stored in the address.

Such an algorithm is called a hash algorithm, therefore, remember, dict stored in the key-value key of the hash must be

Can be changed are not hash, hash means it can not be changed. This is in order to accurately calculate the memory address ⽽ provisions.

Hashable known (non-variable) data types: int, str, tuple, bool not hash (variable) data types: list, dict, set

语法:{'key1':1,'key2':2}

Note:. Key must be immutable (hashable) the value does not require any type of data can be stored.

# 合法
dic = {123: 456, True: 999, "id": 1, "name": 'sylar', "age": 18, "stu": ['帅
哥', '美⼥'], (1, 2, 3): '麻花藤'}
print(dic[123])
print(dic[True])
print(dic['id'])
print(dic['stu'])
print(dic[(1, 2, 3)])

# 不合法
# dic = {[1, 2, 3]: '周杰伦'} # list是可变的. 不能作为key
# dic = {{1: 2}: "哈哈哈"} # dict是可变的. 不能作为key
dic = {{1, 2, 3}: '呵呵呵'} # set是可变的, 不能作为key

Note:... Dict saved data is not maintained in accordance with our order is added to it in order of hash tables to hold the ⽽ hash table is not continuous so is not supported while slicing ⼯ as it can only be obtained through the key of dict. data
dictionary definition of ways:

dict(key=1,key1=2,key2=3)

Random deleted

dic = {"key":"value","key2":"value2"}
dic.popitem()  # 随机删除

image-20190711215430029

Here to explain, official documents indicate random delete a key pair, but when we actually test

Delete dictionary is the last key-value pair, which is a Python36 currently exist a bug

Batch create a dictionary

dic = {}
dic1 = dic.fromkeys("abc",[1,2])
print(dic1)

formkeys this is a pit, the pit is that the value of the variable data type is the time when the first key corresponds to the value to be modified later, the rest of the keys corresponding values ​​were also followed changed. How to avoid the pit, bulk is create dictionary can not be used when the value of variable data types.

Dictionary CRUD

increase

dic = {}

dic['name'] = '汪峰'
dic['age'] = 18
print(dic)

结果:
{'name': '汪峰', 'age': 18}
# 如果dict中没有出现这个key,就会将key-value组合添加到这个字典中

# 如果dict中没有出现过这个key-value. 可以通过setdefault设置默认值
s1 = dic.setdefault('王菲')
print(s1)
print(dic)
结果:
None    
# 返回的是添加进去的值
{'王菲': None}  
# 我们使用setdefault这个方法 里边放的这个内容是我们字典的健,这样我们添加出来的结果
就是值是一个None

dic.setdefault('王菲',歌手)    
# 这样就是不会进行添加操作了,因为王菲在dic这个字典中存在
# 总结: 当setdefault中第一个参数存在这个字典中就就不进行添加操作,否则就添加

dic1 = {}
s2 = dic1.setdefault('王菲','歌手')
print(s2)
print(dic1)
结果: 
歌手
{'王菲': '歌手'}

delete

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}
s = dic.pop('哈啥给')   # pop删除有返回值,返回的是被删的值
print(s)

print(dic)    # 打印删除后的字典
dic.popitem()  # 随机删除  python3.6是删除最后一个
print(dic)

dic.clear()  # 清空

change  

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}
dic['哈啥给'] = '剑姬'   # 当哈哈给是字典中的健这样写就是修改对应的值,如果不存在就是添加

print(dic)
dic.update({'key':'v','哈啥给':'剑姬'})

# 当update中的字典里没有dic中键值对就添加到dic字典中,如果有就修改里边的对应的值
print(dic)

check

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}
s = dic['大宝剑']        #通过健来查看,如果这个健不在这个字典中.就会报错
print(s)

s1 = dic.get('剑圣')     #通过健来查看,如果这个健不在这个字典中.就会返回None
print(s1)

s2 = dic.get('剑姬','没有还查你是不是傻')  # 我们可以在get查找的时候自己定义返回的结果
print(s2)

Other dictionary operations

Gets a dictionary of all the key

key_list = dic.keys()    
print(key_list)

结果:
dict_keys(['剑圣', '哈啥给', '大宝剑'])
# 一个高仿列表,存放的都是字典中的key

Get all the values ​​of the dictionary

value_list = dic.values()
print(value_list)

结果:
dict_values(['易', '剑豪', '盖伦'])
#一个高仿列表,存放都是字典中的value

Gets a dictionary of key-value pairs

key_value_list = dic.items()
print(key_value_list)
结果:
dict_items([('剑圣', '易'), ('哈啥给', '剑豪'), ('大宝剑', '盖伦')])

# 一个高仿列表,存放是多个元祖,元祖中第一个是字典中的键,第二个是字典中的值

Loop keys print ancestral form

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}

for i in dic:
    print(i)

for i in dic.keys():
    print(i)

Value of the loop print dictionary

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}
for i in dic:
    print(dic[i])

for i in dic.values():   
    print(i)

Print circulation Ganso form of key-value pairs

dic = {'剑圣':'易','哈啥给':'剑豪','大宝剑':'盖伦'}
for i in dic.items():
    print(i)

Deconstruction

a,b = 1,2
print(a,b)
结果:
1 2

a,b = ('你好','世界')
print(a,b)
结果:
你好 世界

a,b = ['你好','大飞哥']
print(a,b)
结果:
你好 世界

a,b = {'汪峰':'北京北京','王菲':'天后'}
print(a,b)
结果:
汪峰 王菲

Deconstructing the content can be assigned to each variable which we can quickly use deconstruction of the value of the use

The dictionary acquisition cycle keys and values

for k,v in dic.items():
    print('这是键',k)
    print('这是值',v)

结果:
这是键 剑圣
这是值 易
这是键 哈啥给
这是值 剑豪
这是键 大宝剑
这是值 盖伦

Dictionary nesting

dic = {
    'name':'meet',
    'age':48,
    'wife':[{'name':'国际章','age':38}],
    'children':['第一个熊孩子','第二个熊孩子']
}

Gets the name of the wife of meet

d1 = dic['wife'][0]['name']
print(d1)

Gets meet children

d2 = dic['children']
print(d2)

Get the first child meet the

d3 = dic['children'][0]
print(d3)

Guess you like

Origin www.cnblogs.com/luckinlee/p/11619874.html