Python sequence Type--dictionary

Source: Internet
Author: User

Dictionary

  Dictionary dict, the stored element is an unordered key-value pair (K-V), and the K-value of the dictionary is any immutable data type such as: string,

number, tuple), and the V value is any data type. When the data is stored inside the computer, it is represented by a hash table, and the list does not support translating to

The reason for a hash table is that K is variable (the list can be added, deleted, changed), whereas tuples can be represented by a hash table. Due to its disordered nature, the

It is not possible to use slices like a list. But we can make changes to the k-y values in the dictionary. When using a For loop (cannot use while),

By default, only the K value is output and the V value is not output. Of course, the corresponding built-in function is also provided in the dictionary to compensate for this flaw.

It is also important to note that when there are two identical k values in the dictionary , the previous v value is overwritten by the latter v value. Here is an introduction to a typical

For example. For example, when the K value is type bool , the computer considers True to be 1 andFalse to 0 if the k value in front of it has 0 or 1, it will be

Cover it off. At output, True is replaced with 1,false is replaced with 0, which is found in the experiment when this feature is available.

By the means, anon-0 value of type bool will be represented as 1 inside the computer . the value that causes the bool type to be false is 0, empty (

None), empty string ( ""), Empty tuple ( ()), empty list ( []), Empty dictionary ( {}), empty collection ( set ()).

1. Create a dictionary

#Create a dictionaryinfo = {    "K1": 1,    "K2": 2,    "K3": 3,       4:444,       5: True,6:6,    "K7":["a","b","C","D"],    "K8":("e","F","g","h",),    }#TestPrint(info['K1'])#Take valuePrint(info[4])Print(info["K7"][2])delinfo["K7"][2]#Delete kPrint(info["K7"])#show what's been deleted

2. simultaneous K - values

info = {       1:1, True:123,#Overwrite the previous V-valuefalse:456,    "K7":["a","b","C","D"],    "K7":("e","F","g","h",),#Overwrite the previous V-value    }Print(info)#output: {1:123, ' K7 ': (' e ', ' f ', ' g ', ' H ')}

3. built-in functions

3.1 Fromkeys(*args, **kwargs) function: is a static method

# creates a dictionary from a sequence, specifying a uniform value of v = dict.fromkeys (["K1","K2" by **kwargs) ,"K3"],"See")print(v)   # output: {' K1 ': ' See ', ' K2 ': ' See ', ' K3 ': ' See '}

3.2 SetDefault() function: Sets the default value, or returns the value that already exists if the values set already exist

Dic_ky = {"K1":"001","K2":"002"}v1= Dic_ky.setdefault ('K3','003')#K3 does not exist, returns a value after inserting the dictionaryV2 = Dic_ky.setdefault ('K1','111')#Setup failed, return to the original value of the dictionary K1 001Print(v1)#Output: 003Print(v2)#Output: 001

3.3 Update () function: Updating dictionaries

#The first of these methodsDic_ky = {"K1":"001","K2":"002"}dic_ky.update ({'K1':'111','K2': 222})Print(Dic_ky)#output: {' K1 ': ' 111 ', ' K2 ': 222}#The second method ofDic_ky.update (k1='a', k2='b', k3='C', k4='D')Print(Dic_ky)#output: {' K1 ': ' A ', ' K2 ': ' B ', ' K3 ': ' C ', ' K4 ': ' d '}

3.4 keys function: Fetch k value

 for inch Info.keys ():     Print (i)

3.5 VALUES () function: Take the V value

 for inch info.values ():     Print (i)

3.6 Items() function: Take k-v value, use two iteration variables to loop k,v

 for inch Info.items ():     Print (K,V)

3.7 Get(d=none) function: safe accessor, no error when fetch K is not present

v = info.get ('k',"ERROR")  #  The error is the value returned when it is not present, and if the parameter is ignored, the Noneprint(v)                # output: ERROR

3.8 pop () function: The V of the specified K value is deleted, and the return value can receive the deleted V value

v = info.pop ('k',"error")  #error is not present when the value returned Returns the Noneprint(v)                # output: ERROR If the parameter is ignored

3.9 Popitem() function: Returns a randomly deleted key-value pair

K,v = Info.popitem ()  # returns the randomly deleted key-value pair print(k,v)          # output: K8 (' e ', ' f ', ' G ', ' H ')

The 3.10 Clear() function and the copy() function are no longer listed ...

Python sequence Type--dictionary

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.