Data type python learning (dic)

Dictionary 3.8

3.8.1 Introduction dictionary

Dictionary (dict) python is the only type of a map. He is enclosed in {} key-value pairs in the key is unique dict. When saving, according to a key memory address is calculated, and then the key-value stored at this address, this algorithm is called hash algorithm. Therefore, key-value stored in the key in the dict must be a hash, you can change the hash is not, then it means that the hash can not be changed. This is in order to calculate accurate and the memory address specified. Hashable known (non-variable) data types: int, str, tuple, bool
not hash (variable) data types: list, dict, set
syntax:
** {key1: VALUE1, key2: value2. ...}
Note: ** key must be immutable (hashable) is, value is not required. You can save any type of data, because of the presence of the key, the dictionary query efficiency is very high.

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}: "哈哈哈"} # dict是可变的. 不能作为key
dic = {[1, 2, 3]: '周杰伦'} # list是可变的. 不不能作为key
dic = {{1, 2, 3}: '呵呵呵'} # set是可变的, 不能作为key

dict saved data is not stored in accordance with the order we added to it, is saved in the order hash table, and the hash table is not continuous, so you can not slice the work, it can only be acquired through key data in dict

3.8.2 Dictionary related operations

1. Increase

General: dic [key] = value

#增加
dic = {}
dic['name'] = '周润发' # 如果dict中没有出现这个key, 就会新增一个key-value的组合进dict
dic['age'] = 18
print(dic)

Irreplaceable: dic.setdefault ( 'Key', 'value')

If the key had already appeared in the dictionary, then this command will not be able to increase operating.

# 如果dict中没有出现过这个key-value. 可以通过setdefault设置默认值
dic.setdefault('盖伦') # 也可以往里面设置值
dic.setdefault("盖伦", "德玛西亚") # 如果dict中已经存在了,那么setdefault将不会起作用
print(dic)
2. Delete

dic.popitem () # immediately deleted

dic.pop ( 'Key') # delete orientation

dock [Key] #del 删

dic.clear () # Empty

Note: When the dictionary in an iterative process, not the delete operation, because iterations are unordered.

3. modify, and query

modify

dic [ 'Key'] = new value

dic.update (DIC2) # DIC2 coincides with the Key in the key dic, replacement value; DIC2 if the key does not exist in the dic, the new key-value pair in the dic; dic if there is not DIC2 key is the key to remain unchanged.

Inquire

Print (DIC [Key]) #key being given the absence of

print (returns (key, key does not exist dic.get content) #key return None absent when the return value is customizable

setDefault () . ##. 1 added (there is no look Key, if there is a direct query; if not, and returns the new value) 2. The key return value to the value of

4. Loop
Dictionary traversal --keys ()
###字典的遍历
dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
print(dic.keys())   #因列表的形式输出
for key in dic.keys():
    print(key)  #拿到key
    print(dic[key])   #拿到value,实现对value的遍历
Dictionary traversal --values ​​()

Note: You can find the value by value by key but can not find the key! !

dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
print(dic.values())   #通过value是拿不到Key的
for value in dic.values():  #只能遍历value
    print(value)
Dictionary traversal - key to items ()
dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
print(dic.items())
for item in dic.items():
    print(item)  #输出的是元组
    print(item[0],item[1])
Dictionary traversal - Brain Road Qing Qi version

Firstly, a solution package small knowledge, the number unpack the number of variables must be front and behind unpacked must be consistent

a,b = (10,20)  #解构,解包,元组、列表都具有该功能
print(a)  
print(b)
###前边变量的个数必须与后边解包的个数必须一致

Realization : When you need to traverse the dictionary, involving key and value in operations, direct version is the best choice

#含蓄版
dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
for item in dic.items():
    k,v = item
    print(k)
    print(v)
#直接版
dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
for k,v in dic.items():
    print(k)
    print(v)
Iterative version of the dictionary traversal --key

Because the object dictionary is itself an iterative loop can be made for direct

#先看一下如果直接对字典进行迭代的话会是什么情况
dic = {'盖伦':'德玛西亚','戴安娜':'月光女神','猴哥':'齐天大圣'}
for el in dic:
    print(el)  #直接输出的只有Key,那么是不是可以用key把value给印出来呢?
    print(dic[el])  #答案是可以的
The nested dictionaries

When writing nested dictionary, it should pay more attention between the elements and the elements do not forget to add a comma.

dic = {
    'name' : '盖伦',
    'age'  : 24,
    'slogan' :'德玛西亚',
    'family': {
            '皇子' : '嘉文四世',
            '总管' : '赵信',
            '女警' : {
                'name' : '凯特琳',
                'age'  : 23 ,
                'slogan':'我,miss,怎么可能'
                    }
                } ,
    'equipment': [

        {'num1':'黑切','use':'kill','gank':'Yes'},
        {'num2':'日炎','use':'堆肉','gank':'No'}
                    ]
        }
print(dic['equipment'][1]['gank'])  #查看盖伦第二个装备是否适合gank
dic['family']['总管'] = dic['family']['总管'] + '总管'  #修改德邦的信息
print(dic['family']['总管'] )

Guess you like

Origin www.cnblogs.com/jjzz1234/p/10991474.html