SoFunction
Updated on 2024-10-30

A brief talk about Tuples and Dictionaries in Python

preamble

This article documents some understanding of Python's data types Tuple and Dictionary, as well as an introduction to some of the built-in methods. Without further ado, let's take a look at the details.

Genesis Tuple

Features:Data within a metazoan is immutable

Definition of an element: T = (1, )

>>> T=(1,)
>>> type(T)
<type 'tuple'>

Special metazoans: "variable" metazoans

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

It looks like the tuple has changed, but what has really changed is that the elements within the list [1, 2, 3] have changed, but the memory address of this list in the tuple T is unchanged.

Conclusion: the actual elements of the meta-ancestor contain mutable elements, but the memory addresses of the elements in the meta-ancestor do not change, so the so-called meta-ancestor immutable means that the memory addresses pointed to by the elements are unchanged

Dictionary Dict

Features:

1, Dictionary is the only type of mapping 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, Hash is characterized by the KEY to calculate the storage, if the KEY is variable, will lead to data confusion.

>>> 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' (Here's a hint.listis not to beHashCalculated data types,on account oflistis a variable data type)
>>>

As you can see from this error, you can only use immutable objects for the keys of a dictionary (meta-ancestors are allowed), but there is no requirement to use immutable objects for the values of a dictionary.

Key-value pairs are split with a colon ':', each pair is separated by a comma ',', and all of these are enclosed in braces '{}'

The key-value pairs in the dictionary are not sequential, so they cannot be accessed by indexes, but only by the key to obtain the corresponding value.

(Expansion: if the same key occurs during the definition process, the last key-value pair is retained when the final storage is done)

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

Creation and Access

First way to create: directly by including key-value pairs in curly braces

The second way to create: using built-in functionsdict()to create, note!dict()There can only be one parameter in parentheses, to enclose all key-value pairs

(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) Keyword parameters can also be specified

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

The lowercase 'vimiix' here should not be enclosed in single quotes, adding them will report an error!

(3) The built-in method .fromkeys of dict has two arguments

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

The actual production process is created using dictionary generative, which generates the corresponding data based on the existing data that is available.

Dictionary generative 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 chestnut, but not the ideal answer, pending learning how to generate one-to-one key-value pairs

Dictionary's built-in methods:

get() :

Get the value corresponding to the key, return None if not found, return the corresponding value if found.

pop(key) :

pops up the value corresponding to the key, defaults to the last one

popitem() :

Randomly returns and deletes a pair of keys and values (items) from a dictionary. Why is it random? Because dictionaries are unordered, there is no such thing as "last item" or any other order. If you need to delete items one by one, you can use thepopitem()The method is efficient.

update() :

Update or add a new key-value pair (if it's there, it's there)

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

summarize

The above is the entire content of this article, I hope that the content of this article on your learning or work can bring some help, if there are questions you can leave a message to exchange, thank you for my support.