day8-python tuples, dictionaries, collections.

Keywords: REST Python less

Article Directory


Today is the eighth day, to share with you the following in python:

Tuples, Dictionaries and Collections

1. Tuples

1. What is a tuple

Tuples are immutable lists
Tuples are also container-type data types, with () as the flag of the container and multiple elements separated by commas: (Element 1, Element 2, Element 3, Element 4,...)
Tuples are immutable (no additions or deletions are supported); tuples are ordered (subscript operations are supported)
Elements in tuples have the same requirements as lists

1) Empty tuples: ()
tuple1 = ()
print(type(tuple1))
2) Tuples of a single element: (element)
list1 = [10]    # List of individual elements
tuple2 = (10)
print(tuple2, type(tuple2))    # 10 <class 'int'>

tuple3 = (10,)
print(tuple3, type(tuple3))    # (10,) <class 'tuple'>
3) Tuples of multiple elements:

a. Variable= (Element 1, Element 2, Element 3,...)

tuple4 = (100, 200, 300)
print(tuple4, type(tuple4))    # (100, 200, 300) <class 'tuple'>

b. Variable = Element 1, Element 2, Element 3,...

tuple5 = 10, 20, 30, 40
print(tuple5, type(tuple5))    # (10, 20, 30, 40) <class 'tuple'>

2. Get the elements in the tuple

1) List of ways to get elements tuple support

A. Get a single element

names = 'The Big Bang Theory', 'Game of Rights', 'Vampire Diaries', 'Two Broke Girls', 'Brotherly Company', 'Nikita'
print(names[-2])

b. Slices

print(names[1::2])    # ('Game of Rights','Broken Sister','Nikita')

c. Traversal

for x in names:
    print(x)

print('=========================')
for index in range(len(names)):
    print(names[index])
2) Other ways (the same applies to lists)

a. Variable 1, variable 2, variable 3,...=tuple
Note: The number of variables here should be the same as the number of elements in the tuple

tuple6 = (10, 78, 45)
x, y, z = tuple6
print(x, y, z)    # 10 78 45

num1, num2 = 100, 200     # num1, num2 = (100, 200)

b. Variable 1, variable 2, variable 3,...=tuple
The number of preceding variables is less than the number of tuples in the tuple, and there is only one variable preceded by *

person = ('Yu Ting', 'female', 18, 100, 89, 50)
name, gender, age, *num = person
print(name, gender, age)   # Yu Ting Nu 18
print(num)     # [100, 89, 50]


*x, y, z = 10, 90, 89, 78, 89
print(y, z)     # 78 89
print(x)       # [10, 90, 89]

a, b, *c, d, e = 1, 2, 3, 4, 5, 6, 7, 8, 9
print(a, b)    # 1 2
print(d, e)    # 8 9
print(c)       # [3, 4, 5, 6, 7]
Supplement: * Unpack function
list1 = [10, 20, 30]
print(*list1)    # 10 20 30   print(10, 20, 30)

3. List-related operations apply to all elements

=========================

2. Dictionaries

Define a variable to hold a student's information:

stu = ['Zhang San', 30, 'male', '10011', 170, 65, 60]
print(stu[1])
print(stu[-1])

stu = {'name': 'Zhang San', 'age': 30, 'gender': 'male', 'id': '10011', 'height': 170, 'weight': 65, 'score': 60}
print(stu['name'])
print(stu['height'])

0.When to use the dictionary

a. Multiple data needs to be saved at the same time
b. Multiple data have different meanings (need to be differentiated)

1. What dictionary (dict)

A dictionary is a container data type, with {} as the flag of the container and multiple elements separated by commas (dictionary elements are key-value pairs): {Key 1:Value 1, Key 2:Value 2, Key 3:Value 3,...}
Dictionaries are mutable (additions and deletions are supported); dictionaries are out of order (subscript operations are not supported)

Elements in a dictionary: key-value pairs
Key-immutable; unique (usually string)
Value - Any type of data that can be repeated
When a dictionary saves data, what it really wants to save is the value, and the key is to distinguish and explain the value.

Empty Dictionary

dict1 = {}

dict2 = {2: 23, 'abc': 'hello', (1, 2): 200}
print(dict2)

Dictionary key is immutable

# dict3 = {[1, 2]: 100, 'abc': 200}     # Report errors
# print(dict3)

dict3 = {'a': 10, 'b': 20, 'a': 100}
print(dict3)    # {'a': 100, 'b': 20}

print({'a': 'b', 'c': 'd'} == {'c': 'd', 'a': 'b'})    # True

2. Get the value of the dictionary

1) Get the corresponding value of a single element
a. Dictionaries[key]  -  Get the specified in the dictionary key Corresponding values(If key No error occurs)

dog = {'name': 'Finance', 'age': 3, 'breed': 'Poodle', 'gender': 'mother', 'weight': 10}
print(dog['name'])
print(dog['gender'])
# print(dog['height'])      # KeyError: 'height'

b.
Dictionary.get(key) - Gets the value corresponding to the specified key in the dictionary (returns None if the key does not exist without error)
Dictionary.get(key, default) - Gets the value corresponding to the key specified in the dictionary (returns the default value if the key does not exist)

print(dog.get('breed'))
print(dog.get('height'))     # None

print(dog.get('age', 0))     # 3
print(dog.get('height', 40))     # 40
2) Traversal

a. Traversal methods that need to be mastered and applied (most efficient)
for variable in dictionary:
Circulatory body

Note: Variables take all key s in the dictionary

dog = {'name': 'Finance', 'age': 3, 'breed': 'Poodle', 'gender': 'mother', 'weight': 10}
for x in dog:
    print(x, dog[x])

b. Two other scenarios 1 (know)
for variable in dictionary.values():
Circulatory body

The variable takes all the values in the dictionary

for x in dog.values():
    print(x)

c. Two other scenarios 2 (know)
for variable 1, variable 2 in dictionary.items():
Circulatory body

Variable 1 takes all the key s in the dictionary, and variable 2 takes all the values in the dictionary

for x, y in dog.items():
    print(x, y)

print(dog.items())

3. Dictionary additions and deletions

Add/Change
Syntax 1:
Dictionary [key] =value

If the key exists, change the value corresponding to the key to the specified value (change)
If key does not exist, add a key-value pair as'key:value'(increment)

Grammar 2:
Dictionary.setdefault (key, value) - Add key-value pairs (no modification)

movie = {'name':'Journey to the West','time':'1978-10-23','director':'Wu Cheng En'}
print(movie)
change
movie['time'] = '1989-10-25'
print(movie)

# increase
movie['score'] = 9.0
print(movie)

# Will not be modified
movie.setdefault('score', 8.0)
print(movie)    # 'score': 9.0

# Can increase
movie.setdefault('type', 'Myth')
print(movie)
Delete
1)del
 del Dictionary [key] - Deletes the key-value pairs corresponding to the specified key (key does not exist and errors will be reported)
"""
Movie = {name':'Journey to the West','time':'1989-10-25','director':'Wu Cheng En','score': 9.0,'type':'Myth'}
del movie['director']
print(movie)


2)pop
 Dictionary.pop(key) - Removes the value corresponding to the key specified in the dictionary and returns the extracted value

value = movie.pop('type')
print(movie, value)

Dictionary-related operations

Dictionaries do not support addition and multiplication

1) Comparison operation

Dictionaries only support comparison equals and do not support comparison sizes

print({'a': 1, 'b': 2} == {'b': 2, 'a': 1})   # True
2)in and not in

Data in Dictionary - Determines whether a specified key exists in the dictionary
Data not in Dictionary - Determines if the specified key does not exist in the dictionary

cat = {'name': 'tearful', 'age': 2, 'color': 'white'}
print('name' in cat)      # True
print('tearful' in cat)       # False
3) correlation function

A. len - Count the number of key-value pairs in the dictionary

print(len(cat))     # 3

B. dict - Convert custom data into a dictionary

Data requirements: 1. Container data type 2. Containers (small containers) where there are only two elements in the data 3. The first element in a small container is immutable

x = [(1, 2), (3, 4), [5, 6]]
dict1 = dict(x)
print(dict1)    # {1: 2, 3: 4, 5: 6}

x = ('ab', 'cd', 'xy', ['name', 'Zhang San'])
dict2 = dict(x)
print(dict2)    # {'a':'b','c':'d','x':'y','name':'Zhang San'}

c. Dictionary swapping for other data types
Bool - empty dictionary will be converted to False, all others are True
List - All key s in a dictionary are used as elements of the list
Tuple - Element with all key s of the dictionary as tuples

cat = {'name': 'tearful', 'age': 2, 'color': 'white'}
print(list(cat))     # ['name', 'age', 'color']

2. Related Methods

1) Dictionary. clear() - Empty Dictionary
cat.clear()
print(cat)     # {}
2) Dictionary.copy() - Copy the dictionary to produce a new dictionary and return it
cat = {'name': 'tearful', 'age': 2, 'color': 'white'}
cat1 = cat
cat1['name'] = 'Imida'
print(cat)     # {'name':'mimi','age': 2,'color':'white'}

cat = {'name': 'tearful', 'age': 2, 'color': 'white'}
cat2 = cat.copy()
cat2['name'] = 'Imida'
print(cat)    # {'name':'flower','age': 2,'color':'white'}
3)dict.fromkeys()

Dict.fromkeys(Sequence) - Create a new dictionary whose key is the element in the sequence and whose value is None
Dict.fromkeys(Sequence, Value) - Creates a new dictionary whose key is the element in the sequence and whose value is the specified value

dict3 = dict.fromkeys('abc')
print(dict3)    # {'a': None, 'b': None, 'c': None}

stu = dict.fromkeys(['name', 'age', 'gender', 'tel', 'address', 'score'])
print(stu)   # {'name': None, 'age': None, 'gender': None, 'tel': None, 'address': None, 'score': None}

message = ['Zhang San', 'Li Si', 'King Five']
for name in message:
    new_stu = stu.copy()
    new_stu['name'] = name
    print(new_stu)

stu2 = dict.fromkeys(['name', 'age', 'gender', 'tel', 'address', 'score'], 0)
print(stu2)   # {'name': 0, 'age': 0, 'gender': 0, 'tel': 0, 'address': 0, 'score': 0}
4) items, keys, values

Dictionary.keys() - Gets all keys of a dictionary and returns a container (this container is not a list)
Dictionary.values() - Gets all the values of a dictionary and returns a container (this container is not a list)
Dictionary.items() - Gets all keys and values of a dictionary and returns a container where elements are tuples and each tuple corresponds to a key-value pair (this container is not a list)

cat = {'name': 'tearful', 'age': 2, 'color': 'white'}
print(cat.keys())    # dict_keys(['name', 'age', 'color'])
print(cat.values())  # dict_values(['Flowers', 2,'White'])
print(cat.items())   # dict_items([('name','flower', ('age', 2), ('color','white')))
5) update

Dictionary.update - Update the original dictionary with a dictionary produced by the sequence (Update: Add if it does not exist, modify if it exists)

dict4 = {'a': 10, 'b': 20, 'c': 30}
dict4.update({'a': 100, 'd': 40})
print(dict4)   # {'a': 100, 'b': 20, 'c': 30, 'd': 40}

3. Collection

1. What is a set

Collection is a container data type, with {} as the flag of the container and multiple elements separated by commas: {Element 1, Element 2, Element 3,...}
Collections are mutable (supporting additions and deletions); collections are out of order

Elements in a set are immutable and unique

Empty Set
empty = set()    # {} is an empty dictionary
Non-empty set
set1 = {1, 23, 34}

set2 = {(1, 2), 3, 4}

# set3 = {[1, 2], 3, 4}    # Lists cannot be elements of a collection

set4 = {1, 2, 3, 1, 4, 1}
print(set4)    # {1, 2, 3, 4}

print({1, 2, 3} == {2, 3, 1})   # True (description set out of order)

2. Additions and deletions of elements in a collection

1) Check

Collections cannot get individual elements directly, they can only traverse

for variable in set:
Circulatory body

A variable takes every element in a collection

nums = {23, 34, 90, 89}
for x in nums:
    print(x)
2) Increase

a.Collection.add (element) - Add the specified element to the collection
b.Set.update (sequence) - Add all elements in the sequence to the set

nums.add(100)
print(nums)   # {34, 100, 23, 89, 90}

nums.update('abc')
print(nums)   # {34, 100, 'c', 'b', 23, 89, 90, 'a'}

nums = set()
nums.update({'a': 10, 'b': 20})
print(nums)    # {'a', 'b'}
3) Delete

Collection.remove (element) - Delete the element specified in the collection (element does not exist will error)
Collection.discard (element) - Deletes the element specified in the collection (element does not exist without error)

nums = {10, 89, 76, 90, 34}
# nums.remove(10)
nums.discard(10)
print(nums)

# nums.remove(100)  # Report errors
nums.discard(100)   # No error
4) Change - Collection cannot modify elements

3. Mathematical set operations

Sets in python support mathematical set operations: & (intersection), | (union), - (difference set), symmetric difference set (^), >/< (determine whether it is a true subset)

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8, 9}
1) Intersection: Find the common part of two sets
print(set1 & set2)    # {4, 5}
2) Union: Two sets merge into one set
print(set1 | set2)    # {1, 2, 3, 4, 5, 6, 7, 8, 9}
3) Difference sets: set 1 - Set 2 set 1 except the rest of set 2
print(set1 - set2)   # {1, 2, 3}
print(set2 - set1)   # {8, 9, 6, 7}
4) Symmetric difference sets: remove the rest of the common part of the two sets
print(set1 ^ set2)   # {1, 2, 3, 6, 7, 8, 9}
5) True Subset
# Set 1 > Set 2 - Determines if Set 2 is a true subset of Set 1
# Set 1 <Set 2 - Determines if Set 1 is a true subset of Set 2
print({100, 200, 300, 400} > {10, 20})   # False
print({1, 10, 20} > {10, 20})    # True
print({10, 20} > {10, 20})       # False

Okay, that's it today.Bye-bye~

Posted by suresh_m76 on Wed, 17 Jun 2020 09:25:45 -0700