This article mainly introduces the relevant information about Tuple and Dict in Python. The article introduces it in great detail through example code. I believe it has certain reference value for everyone. Friends who need it can come and join us. Let's see.
Preface
This article records some understanding of Tuple and Dict among Python data types, as well as some built-in Introduction to methods. Not much to say below, let’s take a look at the detailed introduction.
Tuple
Features: The data within the Tuple is immutable
Definition of an element : T = (1,)
>>> T=(1,) >>> type(T) <type 'tuple'>
Special ancestor: "variable" ancestor
>>> T=(1,2,3,[1,2,3]) >>> T[3][2] = 'vimiix' >>> T (1, 2, 3, [1, 2, 'vimiix'])
It seems that the ancestor has changed, but what really changed is [1, 2, 3] The elements in this list have changed, but the memory address of this list in the ancestor T has not changed.
Conclusion: Actually, the elements of the Yuanzu contain variable elements, but the memory address of the elements in the Yuanzu has not changed. Therefore, the so-called immutability of the Yuanzu means that the memory address pointed to by the element does not change.
Dictionary Dict
Features:
1. Dictionary is the only mapping type in Python
2. The key of the dictionary (KEY) must be an immutable object -> Because the dictionary is stored in the computer through the Hash algorithm, the characteristic of Hash is that the KEY is calculated and stored. If the KEY is variable, it will cause The data is messy.
>>> D = {1:3,'vimiix':88} >>> type(D) <type 'dict'>
>>> D={[1,2,3]:100} Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> D={[1,2,3]:100} TypeError: unhashable type: 'list' (这里提示list是不能被Hash计算的数据类型,因为list是可变的数据类型) >>>
As can be seen from this error, the keys of the dictionary can only use immutable objects (the ancestor is OK), but there is no such requirement for the values of the dictionary
Key value Pairs are separated by colon ':', each pair is separated by comma ',', and all of them are enclosed by curly braces '{}'
The key-value pairs in the dictionary are not in order , so it cannot be accessed by index, and the corresponding value can only be obtained through the key
Extension: If the same key appears during the definition process, the last key-value pair will be retained during the final storage)
>>> D= {1:2,1:3} >>> D {1: 3}
Creation and access
The first way to create: Create directly by including key-value pairs in curly braces
Two creation methods: Use the built-in function dict()
to create, pay attention! dict()
There can only be one parameter in the brackets, all key-value pairs must be enclosed
(1)
>>> D =dict((1,2),(3,4),(5,6)) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> 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 keywords Parameter
>>> D=dict(vimiix = 'VIMIIX') >>> D {'vimiix': 'VIMIIX'}
The lowercase 'vimiix' here cannot be added with single quotes, otherwise an error will be reported!
(3) dict's built-in method .fromkeys has two parameters
>>> D = dict.fromkeys((1,'vimiix'),('common','value')) >>> D {1: ('common', 'value'), 'vimiix': ('common', 'value')} >>>
In the actual production process, dictionary generation is used to create, and the corresponding data is generated based on the existing data. Data, data is meaningful.
Dictionary generative chestnut:
>>> 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 chestnut, but it is not an ideal answer. We need to learn how to generate one-to-one key-value pairs
Built-in method of dictionary:
get()
:
Get the value corresponding to the key. If it is not found, it returns None. If it is found, it returns the corresponding value. Value
pop(key)
:
Pops the value corresponding to the key, the default is the last one
popitem()
:
Randomly returns and deletes a pair of keys and values (items) in the dictionary. Why is it deleted randomly? Because dictionaries are unordered, there is no so-called "last item" or other order. If you encounter work that requires deleting items one by one while working, it is very efficient to use the popitem()
method.
update()
:
Update or add a key-value pair (if there is one, change it if there is none, or encourage it)
>>> D.update({'newitem':'update'}) >>> D {'newitem': 'update', 1: 'vimiix', 2: 'vimiix', 3: 'vimiix'}
Summarize
The above is the detailed content of Detailed analysis of Tuple and Dict in Python. For more information, please follow other related articles on the PHP Chinese website!