Detailed analysis of Tuple and Dict in Python

Source: Internet
Author: User
This article mainly introduces information about Tuple and Dict in Python. the sample code in this article is very detailed and I believe it will be of reference value to everyone, let's take a look. This article mainly introduces information about Tuple and Dict in Python. the sample code in this article is very detailed and I believe it will be of reference value to everyone, let's take a look.

Preface

This article records some knowledge about Tuple and Dict in Python data types, as well as some built-in methods. I will not talk about it below. let's take a look at the detailed introduction.

Yuanzu Tuple

Features:The data in the ancestor is unchangeable.

Definition of an element: T = (1 ,)

>>> T=(1,)>>> type(T)
 

Special ancestor: "mutable" ancestor

>>> T=(1,2,3,[1,2,3])>>> T[3][2] = 'vimiix'>>> T(1, 2, 3, [1, 2, 'vimiix'])

It seems that the original database has changed, but the elements in the [1, 2, 3] list have changed, but the memory address of the list in the T ancestor has not changed.

Conclusion: Actually, the element of the ancestor contains a variable element, but the memory address of the element in the ancestor does not change. Therefore, the so-called immutable ancestor means that the memory address pointed to by the element remains unchanged.

Dictionary Dict

Features:

1. the dictionary is the only ing type in Python.

2. the dictionary KEY (KEY) must be an unchangeable object-> because the dictionary is stored by the Hash algorithm in the computer, the Hash feature is that the KEY is used for computing and storage, if the KEY is variable, Data confusion occurs.

>>> D = {1:3,'vimiix':88}>>> type(D)
 
>>> D = {[1, 2, 3]: 100} Traceback (most recent call last): File"
 
  
", Line 1, in
  
   
D = {[100, 3]:} TypeError: unhashable type: 'list, because list is a variable data type) >>>
  
 

From this error, we can see that the dictionary key can only use immutable objects (the ancestor is acceptable), but it does not have this requirement for the dictionary value.

Key-value pairs are separated by colons (:), and each pair is separated by commas (,). All these are included in braces '{}'.

The key-value pairs in the dictionary have no order, so they cannot be accessed using indexes. Instead, they can only obtain the corresponding values through keys.

Extended: if the same key exists during the definition process, the last key-value pair will be retained during storage)

>>> D= {1:2,1:3}>>> D{1: 3}

Create and access

Method 1: directly create a key-value pair using curly brackets

Method 2: Use built-in functionsdict()!dict()There can only be one parameter in the brackets. you must enclose all key-value pairs.

(1)

>>> D =dict((1,2),(3,4),(5,6))Traceback (most recent call last): File "
 
  ", line 1, in 
  
    D =dict((1,2),(3,4),(5,6))TypeError: dict expected at most 1 arguments, got 3>>> D =dict(((1,2),(3,4),(5,6)))>>> D{1: 2, 3: 4, 5: 6}
  
 

(2) You can also specify the keyword parameter

>>> D=dict(vimiix = 'VIMIIX')>>> D{'vimiix': 'VIMIIX'}

The lower-case 'vimiix 'cannot be enclosed in single quotes. if it is added, an error is returned!

(3) the built-in dict method. fromkeys has two parameters.

>>> D = dict.fromkeys((1,'vimiix'),('common','value'))>>> D{1: ('common', 'value'), 'vimiix': ('common', 'value')}>>>

In the actual production process, the dictionary-based creation is used to generate the corresponding data based on the existing data. it makes sense to have data.

Dictionary-generated chestnuts:

>>> L1 = [1,2,3]>>> L2 = ['a','v','vimiix']>>> D={a:b for a in L1 for b in L2}>>> D{1: 'vimiix', 2: 'vimiix', 3: 'vimiix'}

This is just a generative method, but it is not an ideal answer. you need to learn how to generate one-to-one key-value pairs.

Built-in Dictionary methods:

get() :

Obtains the value corresponding to the key. if None is not found, the corresponding value is returned.

pop(key):

The value corresponding to the key is displayed. the default value is the last one.

popitem():

Returns and deletes a random key and value (item) in the dictionary ). Why random deletion? Because the dictionary is unordered, there is no so-called "last item" or other order. If you need to delete items one by one at work, usepopitem()The method is very efficient.

update():

Update or add a key-value pair)

>>> D.update({'newitem':'update'})>>> D{'newitem': 'update', 1: 'vimiix', 2: 'vimiix', 3: 'vimiix'}

Summary

The above is a detailed explanation of Tuple and Dict in Python. For more information, see other related articles in the first PHP community!

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.