[Python3] Dictionary (dictionary)

Source: Internet
Author: User

Overview

Dictionnary (dictionary) is the most commonly used data type of Python, which is identified by the square brackets {}, whose elements correspond to Key-value, key and value are separated by a colon: split open, let's look at a basic dictionary creation example:

Dict = {u"key1": U"value1", u"key2" : U"value2"}

Or create it like this:

Dict = {12:u" Blog Park ", u"cnblog": U" Gubei " }
Built-in functions

The built-in functions commonly used in Python are:

    • Len
      Used to count the number of dictionary elements, that is, the total number of keys

    • Str
      Output dictionary, which is a printable string output dictionary

    • Type
      Returns the type of the variable

Let's take a look at how the above three functions apply to the instance Code of the dictionary:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":        #Dictionary Basic ExampleDict = {u"Blog Park": U"Cnblog", u"Gubei": U"Python3"}            #calculate the length of a dictionary    Print(Len (dict))#output dictionaries as characters, converting dictionaries to stringsStr_d =Str (dict)Print(str_d)Print(dict)#Judging Type    Print(Type (DICT))#Dictionary type    Print(Type (str_d))#string str type

The results of the implementation are as follows:

2{'Blog Park':'Cnblog','Gubei':'Python3'}{'Blog Park':'Cnblog','Gubei':'Python3'}<class 'Dict'><class 'Str'>
Dictionary methods

In Python, there are a number of methods for dictionary processing, let's look at an example:

    • Clear
      Empty dictionary

    • Copy
      Copy Dictionary

    • Fromkeys
      Creates a new dictionary as a Kye, value is the initial value corresponding to all keys

    • Get
      Returns the value of the specified key, or returns the default value if the key does not exist

    • Inch
      Evaluates if key exists, returns true, otherwise false

    • Items
      Returns a tuple that can be traversed, in the form of (Key,value) elements of a tuple

    • Keys
      Returns all keys for the dictionary

    • SetDefault
      If key exists, it returns its corresponding value, otherwise the key and default value are inserted into the dictionary and the default value is returned

    • Update
      Update dictionary

    • Values
      Returns all value values of the dictionary

Let's take a look at the practical application of the above method:

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"Dictionary Method Application Example") Dict_demo= {u"Blog Park": U"Cnblog", u"Gubei": U"Python3"} tup1= [1, 2, 3, 4]            #Copy replication DictionaryDICT_CP =dict_demo.copy ()Print(Dict_demo)Print(DICT_CP)#Fromkeys Creating a dictionaryDict_new = Dict.fromkeys (tup1, U"value")    Print(dict_new)#Get Gets the value of the specified keyvalue1 = Dict_demo.get (u"Blog Park", u"I am the default value") value2= Dict_demo.get (U"Python3", u"I am the default value")    Print(value1)Print(value2)#in, determine if key existsKey = U"Blog Park"RESULT1= keyinchDict_demo result2= keyinchdict_newPrint(RESULT1)Print(RESULT2)#items, returns the dictionary all (key, value) as a tupleItems =Dict_demo.items ()Print(items)#keys returns all keys in the dictionary as a listKeys =Dict_demo.keys ()Print(keys)#SetDefault, if key exists, returns its corresponding value,    #Otherwise, the key and default values are inserted into the dictionary and the default values are returnedSET_RESULT1 = Dict_demo.setdefault (u"Blog Park", u"Setting the value") Set_result2= Dict_demo.setdefault (U"I'm a key ."+ R"I am the value")    Print(SET_RESULT1)Print(SET_RESULT2)Print(Dict_demo)#update, updating the dictionarydict_demo.update (dict_new)Print(Dict_demo)#values, returns all the value in the dictionaryValues =dict_demo.values ()Print(values)

Run the results on your own.

Traverse, modify, delete

Let's take a look at how to iterate, modify, and delete the dictionary.

#-*-coding:utf-8-*-__author__= u'Gubei'if __name__=="__main__":    Print(U"dictionary traversal, modification, and deletion examples") Dict_demo= {u"Blog Park": U"Cnblog", u"Gubei": U"Python3"}            #Traversal Method 1     for(Key, value)inchDict_demo.items ():Print("%s:%s"%(key, value))#Traversal Method 2     forKeyinchDict_demo.keys ():Print("%s:%s"%(Key, Dict_demo[key]))#ModifyDict_demo[u"ebook"] = u"the modified value"    Print(Dict_demo)#Delete the specified element    delDict_demo[u"ebook"]    Print(Dict_demo)#Empty Dictionarydict_demo.clear ()Print(Dict_demo)

Summary
    • The value of a dictionary can store any type of Python object, which can be either a standard type or a custom type, but key cannot.

    • The key of the dictionary is unique and cannot be repeated

    • A dictionary key can be a number, a string, or even a tuple, but you cannot use a list

[Python3] Dictionary (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.