Python study 5th?? Day-2018.6.04 basic data type (DICT)

Source: Internet
Author: User

I. A brief introduction to the dictionary

The Dictionary (dict) is the only type of mapping in Python. He is composed of key-value pairs enclosed in {}. In Dict, key is unique. When saving, a memory address is calculated based on key. Then save the Key-value in this address. This algorithm is called the hash algorithm, so, remember, in the dict stored in the Key-value key ' must be hash, if you do not understand what is hash, temporarily can remember, can change is not hash, then the hash means immutable. This is required to be able to accurately calculate the memory address.

Known hash (immutable) data types: int, str, tuple, BOOL

Non-hash (variable) data types: list, dict, set

Grammar:

{key1:value1, key2:value2 ...}
Note: Key must be immutable (hashed). value is not required. Can save any type of data

#LegalDIC = {123:456, true:999,"ID": 1,"name":'Sylar'," Age": 18,"Stu": ['Handsome','Beauty'], (1, 2, 3):'Twist Rattan'} Print(dic[123]) Print(Dic[true])Print(dic['ID']) Print(dic['Stu']) Print(dic[(1, 2, 3)]) #Not legal#dic = {[1, 2, 3]: ' Jay Chou '}#the list is mutable. Cannot be a key#dic = {1:2}: "Hahaha"}#the Dict is mutable. Cannot be a keyDIC = {1, 2, 3}:'Oh, huh ?'}    #set is variable and cannot be a key

The data saved by Dict is not saved in the order we added. are stored in the order of the hash table. And the hash table is not continuous. So you can't do the slicing work. It can only get the data in Dict by key

Two. Dictionary additions and deletions and other related operations

1. Increase

DIC ={} dic['name'] ='Chow Yun Fat'     #If this key is not present in the dict, a key-value combination of dict dic[' age ' will be added = Print (DIC)#If this key-value is not present in Dict. Default values can be set by SetDefaultDic.setdefault ('Li Ka')#You can also set the value inside.Dic.setdefault ("Li Ka","Real Estate")#if the dict already exists. Then SetDefault will not work.Print(DIC)

2. Delete

Ret=dic.pop ("Jay")print(ret)del dic[" Jay " ]print(DIC)# randomly delete ret=dic.popitem ()#  Clears all contents of the dictionary Dic.clear ()

3. Modifications

DIC = {"ID": 123,"name":'Sylar'," Age": 18} dic1= {"ID": 456,"name":"Twist Rattan","OK":"wtf"} dic.update (Dic1)#Update the contents of the Dic1 to DIC. If the key has the same name. Modify the replacement. If no key exists, it is added.Print(DIC)Print(DIC1)

4. Enquiry
Queries typically use key to find specific data

Print(dic['name'])#print (dic[' Sylar ') # errorPrint(Dic.get ("OK"))Print(Dic.get ("Sylar"))#NonePrint(Dic.get ("Sylar","Cow b"))#Cow b

5. Other related operations

DIC = {"ID": 123,"name":'Sylar'," Age": 18,"OK":"Kobe Bryant"}Print(Dic.keys ())#Dict_keys ([' id ', ' name ', ' age ', ' OK ') do not care what it is. Use as a list for key in Dic.keys (): Print (key)Print(Dic.values ())#Dict_values ([123, ' Sylar ', 18, ' Kobe ']). Also when list is used for value in Dic.values (): print (value)Print(Dic.items ())#dict_items (' id ', ' 123 ', (' name ', ' Sylar '), (' Age ', ' + '), (' OK ', ' Kobe Bryant ')]) This thing is also a list. Only the list is loaded with a tuple. forKey, ValueinchDic.items ():#?? This is deconstruction.    Print(Key, value)

6. Deconstruction

Printprint= [1, 2, 3]    #print(E, F)

# k,v = Dic.popitem () # Dic.popitem () result is a tuple. A tuple can be directly solved to form two values
# print (k)
# print (v)

Three. Nesting of dictionaries

#Wangfeng = {#' name ': ' Wang Feng ',#' age ':#' wife ': {#' name ': ' Zhang Ziyi ',#' age ':#     },#' Children ': [#{' name ': ' Tinker Bell ', ' age ': ten},#{' name ': ' Tinker Bell ', ' age ': +}#     ]# }#The age of Wang Feng's second son#Print (Wangfeng.get ("Children") [1].get ("Age"))#Print (Wangfeng.get ("wife"). Get ("name"))#Print (Wangfeng.get ("name"))

Python study 5th?? Day-2018.6.04 basic data type (DICT)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.