Summary of common usage of Python3 dictionaries

Source: Internet
Author: User

Summary of common usage of Python3 dictionaries

A python dictionary is another mutable container model, and can store any type of object, such as strings, numbers, tuples, and other container models.

First, create a dictionary

A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:

Dict = {'Alice':'2341','Beth':'9102','Cecil':'3258'}#You can also create a dictionary like thisDict1= {'ABC': 456}dict2= {'ABC': 123, 98.6:37}

Attention:

Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).

The key must be unique, but the value does not have to be.

The value can take any data type, but it must be immutable, such as a string, number, or tuple.

Second, access the values in the dictionary

Put the corresponding key into the familiar square brackets, the following example:

Dict = {'Name':'Zara',' Age': 7,'Class':' First'}Print("dict[' Name ']:", dict['Name'])Print("dict[' age ']:", dict[' Age'] )#The result of the above example output:#dict[' Name ': Zara#dict[' age ': 7

If the data is accessed using a key that is not in the dictionary, the output error is as follows:

Dict = {'Name':'Zara',' Age': 7,'Class':' First'}Print("dict[' Alice ']:", dict['Alice'] )#The result of the above example output:#keyerror: ' Alice '

Third, modify the dictionary

The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:

Dict = {'Name':'Zara',' Age': 7,'Class':' First'}dict[' Age'] = 8;#Update Existing entrydict['School'] ="DPS School";#ADD new EntryPrint("dict[' age ']:", dict[' Age'])Print("dict[' School ']:", dict['School'])#The result of the above example output:#dict[' age ': 8#dict[' School ': DPS School

Iv. Deleting a dictionary element

The ability to delete a single element also clears the dictionary, emptying only one operation.

Show Delete a dictionary with the Del command, as in the following example:

Dict = {'Name':'Zara',' Age': 7,'Class':' First'}deldict['Name']#Delete key is ' Name ' entryDict.clear ()#Empty Dictionary All entries keyerror: ' Age 'delDict#Delete dictionary TypeError: ' Type ' object is not subscriptablePrint("dict[' age ']:", dict[' Age'])#but this throws an exception because the dictionary no longer exists after using del

V. Characteristics of dictionary Keys

A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.

Two important points to keep in mind:

1) The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:

Dict = {'Name':'Zara',' Age': 7,'Name':'Manni'}Print("dict[' Name ']:", dict['Name'])#The result of the above example output:#dict[' Name ']: Manni

2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:

Dict = {['Name'Zara'age': 7 }print("", dict['Name'  # The result of the above instance output:#  typeerror:unhashable type: ' List '

Six, dictionary built-in functions & methods

The Python dictionary contains the following built-in functions:

CMP (Dict1, Dict2) #比较两个字典元素.

Len (dict) #计算字典元素个数, which is the total number of keys.

STR (dict) #输出字典可打印的字符串表示.

Type (variable) #返回输入的变量类型 returns the dictionary type if the variable is a dictionary.

Reference Link: https://www.cnblogs.com/scios/p/8108243.html

Determine if key exists in the Python dictionary

There are generally two common practices:

The first approach: using a self-implemented function:

There is a Has_key () method in the property method of the Python dictionary:

# Generate a dictionary d = {'name'' age 'Tel  ': '* * * Print return value  ' D.has_key ' ('name'  )# results return True

The second method: Use the In method:

#Generate a dictionaryD = {'name': Tom,' Age': 10,'Tel': 110}#prints the return value, where D.keys () is the key that lists all the dictionariesPrint' Name 'inchD.keys ()Print 'name' inchD#Two of the results are returned true

In addition to using in, you can determine that the key does not exist and use in is faster than Has_key.

Reference Link: 52160942

The Python dictionary is sorted by value

First, a few solutions, specific time to elaborate

D = {' A ': 1, ' B ': 4, ' C ': 2}

The dictionary is this, and then you want to sort the dictionary by value

Method One:

lambda x:x[1],reverse = True)

Method Two:

Import= operator.itemgetter (1))

Method Three:

F = zip (d.values (), D.keys ()) sorted (f)

The result is [(1, ' a '), (2, ' C '), (4, ' B ')]

Zip, the zip function will sort the first element by default, how do I cancel the sort?

Reference Link: https://www.cnblogs.com/timtike/p/6562402.html

Summary of common usage of Python3 dictionaries

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.