search
HomeBackend DevelopmentPython TutorialDetailed introduction to python tuples and dictionaries

1. Tuple

##1. Tuple expression

(1,2,3,4)
('olive',123)
("python",)
Create tuple:

a=tuple((1,2,3,))
b=("python",)

2. Tuple functionsAttributes

class tuple(object):
    """
    tuple() -> empty tuple
    tuple(iterable) -> tuple initialized from iterable's items
    
    If the argument is a tuple, the return value is the same object.
    """
    def count(self, value): # real signature unknown; restored from __doc__
        """ T.count(value) -> integer -- return number of occurrences of value """
        return 0
    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        T.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0
    def __add__(self, *args, **kwargs): # real signature unknown
        """ Return self+value. """
        pass
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ Return key in self. """
        pass
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
    def __getitem__(self, *args, **kwargs): # real signature unknown
        """ Return self[key]. """
        pass
    def __getnewargs__(self, *args, **kwargs): # real signature unknown
        pass
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
    def __hash__(self, *args, **kwargs): # real signature unknown
        """ Return hash(self). """
        pass
    def __init__(self, seq=()): # known special case of tuple.__init__
        """
        tuple() -> empty tuple
        tuple(iterable) -> tuple initialized from iterable's items
        
        If the argument is a tuple, the return value is the same object.
        # (copied from class doc)
        """
        pass
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<p style="text-align: left;">3. Introduction to some functional attributes of tuples<strong></strong></p>Tuples and lists have Very similar, but the elements of tuples cannot be modified, so many functions that lists have are not available in tuples. <p style="text-align: left;"></p><p style="text-align: left;">1) count(self, value):<span style="background-color: #00ffff"></span></p> Counts the number of value elements in the tuple and returns an int value. <p style="text-align: left;"></p><pre class="brush:php;toolbar:false">a=(1,2,3,4,1,2,3,1,2,)
b=a.count(1)
print(a,type(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) <class>
3 <class>
demo</class></class>

2)index(self, value, start=None, stop=None):

Index, find the value element in the tuple The first appearing position, start and stop parameters are the starting and ending positions of the search. The default is None and the int value is returned. If this element is not included in the search, a ValueError: 'f' is not in tuple is returned.

a=(1,2,3,4,1,2,3,1,2,)
b=a.index(3)
print(a,len(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2) 9
2 <class>
demo</class>

3) add(self, *args, **kwargs):

Add a new element to the tuple. The new element added needs to Add as a tuple, generating a new tuple.

a=(1,2,3,4)
b=a.__add__((5,1))   #括号理给出的必须是元组
print(a,type(a))
print(b,type(b))
#运行结果
(1, 2, 3, 4) <class>
(1, 2, 3, 4, 5, 1) <class>
demo</class></class>

4) contains(self, *args, **kwargs):

Determine whether the tuple contains an element and return Boolean value.

a=(1,2,3,4,1,2,3,1,2,)
b=a.__contains__(2)
c=a.__contains__(5)
print(a)
print(b)
print(c)
#运行结果
(1, 2, 3, 4, 1, 2, 3, 1, 2)
True
False
demo

2. Dictionary

1. Dictionary expression

{"name":"olive","age":18}
Create dictionary:

a={"name":"olive","age":18}
b=dict({"name":"lusi","age":18})

2. Dictionary functional attributes

class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass
    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass
    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Returns a new dict with keys from iterable and values equal to value. """
        pass
    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass
    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass
    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass
    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        If key is not found, d is returned if given, otherwise KeyError is raised
        """
        pass
    def popitem(self): # real signature unknown; restored from __doc__
        """
        D.popitem() -> (k, v), remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if D is empty.
        """
        pass
    def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
        """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
        pass
    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass
    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass
    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if D has a key k, else False. """
        pass
    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass
    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass
    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y)  x[y] """
        pass
    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass
    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass
    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass
    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass
    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass
    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self size of D in memory, in bytes """
        pass
    __hash__ = None
dict

3. Introduction to some functional attributes of the dictionary
1) clear(self):

Clear all elements in the dictionary.

a={"name":"olive","age":18}
b=a.clear()
print(a)
print(b)
#运行结果
{}
None

2) copy(self):

Copy a tuple, which is equivalent to a shallow copy.

a={"name": "olive","age":18}
b=a.copy()
print(a,id(a),id("name"))
print(b,id(b),id("name"))
#赋值
c={"name": "lusi","age":18}
d=c
print(c,id("name"))
print(d,id("name"))
#浅拷贝
e={"name": "shy","age":18}
f=copy.copy(e)
print(e,id(e),id("name"))
print(f,id(f),id("name"))
#运行结果
{'name': 'olive', 'age': 18} 2915224 2019840
{'name': 'olive', 'age': 18} 2915304 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'lusi', 'age': 18} 2019840
{'name': 'shy', 'age': 18} 5584616 2019840
{'name': 'shy', 'age': 18} 5586056 2019840

3) fromkeys(*args, **kwargs):[fromkeys(seq,value=None)]

Create a new dictionary, with seq as The keys of the dictionary, value is the value of the dictionary, and the default is None. Suitable for creating a dictionary of identical values.

a={"hunan": "changsha","guangdong":"guangzhou","jiangsu":"nanjing",'hubei':"wuhan"}
b=dict.fromkeys(a,"good")
c=dict.fromkeys(["a","b","c"],"abc")
d=dict.fromkeys("abcc")           
print(a)
print(b)
print(c)
print(d)
#运行结果
{'guangdong': 'guangzhou', 'hubei': 'wuhan', 'hunan': 'changsha', 'jiangsu': 'nanjing'}
{'hubei': 'good', 'guangdong': 'good', 'hunan': 'good', 'jiangsu': 'good'}
{'c': 'abc', 'b': 'abc', 'a': 'abc'}
{'c': None, 'b': None, 'a': None}   #seq给出的字符串c是重复的,但是创建的键只取一个。

4) get(self, k, d=None):

Get the value with key k in the dictionary, If k is not contained in the dictionary, the value of d is given, and d defaults to None.

a={"a":1,"b":2,"c":3,"d":4}
b=a.get("a")
c=a.get("e")
d=a.get("e",5)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
1
None
5

5)items(self):

A method to traverse the dictionary and combine each pair of key and value in the dictionary A tuple and returns these tuples in a list-like dict_items.

a={"a":1,"b":2,"c":3,"d":4}
b=a.items()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'c': 3, 'a': 1, 'b': 2}
dict_items([('d', 4), ('c', 3), ('a', 1), ('b', 2)]) <class></class>

6) keys(self):

A method to traverse dictionary keys keys and return a list-like dict_keys, which is the same as the items method.

a={"a":1,"b":2,"c":3,"d":4}
b=a.keys()
print(a)
print(b,type(b))
#运行结果
{'b': 2, 'a': 1, 'c': 3, 'd': 4}
dict_keys(['b', 'a', 'c', 'd']) <class></class>

7)values(self):

A method to traverse the dictionary value value and return a list-like dict_values, Same usage as items method.

a={"a":1,"b":2,"c":3,"d":4}
b=a.values()
print(a)
print(b,type(b))
#运行结果
{'c': 3, 'd': 4, 'b': 2, 'a': 1}
dict_values([3, 4, 2, 1]) <class></class>

8)pop(self, k, d=None):

and get method The usage is similar, except that get is to get the value with key k in the dictionary, while pop is to get the value with key k in the dictionary. When the key k is not included in the dictionary and d is not the default value, the value obtained is the d value. If d is the default value None, a KeyError is reported.

a={"a":1,"b":2,"c":3,"d":4}
b=a.pop("a")
c=a.pop("e","five")
print(a)
print(b,type(b))
print(c,type(c))
#运行结果
{'c': 3, 'd': 4, 'b': 2}
1 <class>
five <class></class></class>

9)popitem(self):

从字典中随机取出一组键值,返回一个新的元组。如果字典中无键值可取,则KeyError报错。

a={"a":1,"b":2,"c":3,"d":4}
b=a.popitem()
print(a)
print(b,type(b))
#运行结果
{'d': 4, 'b': 2, 'a': 1}
('c', 3) <class></class>

10)setdefault(self, k, d=None):

从字典中获取键为k的值,当字典中包含键k值时,功能和get基本一致,当字典中不包含键k值时,在原字典上添加上键为k的初始键值对,并返回值d。

a={"a":1,"b":2,"c":3,"d":4}
b=a.setdefault("a")
c=a.setdefault("e")
d=a.setdefault("f",6)
print(a)
print(b)
print(c)
print(d)
#运行结果
{'f': 6, 'c': 3, 'a': 1, 'e': None, 'b': 2, 'd': 4}
1
None
6

11)update(self, E=None, **F):

给字典新增元素,没有返回值。用法:dict.update(dict2)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.update({"e":5})
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4, 'a': 1, 'e': 5}
None

12)contains(self, *args, **kwargs):

判断列表中是否包含某个键值对,返回布尔值。用法:dict.contains(keys)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.__contains__("a")
print(a)
print(b)
#运行结果
{'a': 1, 'd': 4, 'c': 3, 'b': 2}
True

13)delitem(self, *args, **kwargs):

删除字典中的某个键值对,没有返回值。用法:dict.delitem(keys)。

a={"a":1,"b":2,"c":3,"d":4}
b=a.__delitem__("a")
print(a)
print(b)
#运行结果
{'c': 3, 'b': 2, 'd': 4}
None

The above is the detailed content of Detailed introduction to python tuples and dictionaries. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software