# Python Lesson 7: tuples, dictionaries and collections

Posted by RTS on Sat, 19 Feb 2022 06:36:00 +0100

# 1. Tuple

1. A tuple is an immutable sequence
2. The symbol is ()
() can be omitted, but when there are other elements in the tuple, there must be = = ','==
3. tuple1 = () empty tuple
4. Tuples can also store everything
tuple1 = (1, None, False, [])

## Unpacking of tuples

Here is an example to illustrate:

```# Unpacking
tuple1 = (1, 2, 3)
a, b, c = tuple1
print(a, b, c)
```

Calculated: ```# special case
tuple1 = (1, 2, 3, 4)
a, b, c = tuple1
print(a, b, c)
``` An error will be reported here because there are too many values in tuple1 that need to be unpacked.

For this problem, the concept of '* -- wildcard' is introduced

’*'is a wildcard symbol, which can represent all. In addition, it will be converted to list form.

```# Examples of wildcard use
tuple1 = (1, 2, 3, 4)
a, b, *c = tuple1
print(a, b, c)
```

Obtained by operation Supplementary notes

Unpacking of strings and lists is similar to unpacking of tuples.

# 2. Dictionary

1. The data structure is mapping, that is, query.
2. Mapping - one-to-one correspondence.
3. The expression key value is called a key value pair or an item.
4. Dictionary type dict
5. Represents the symbol {}
6. dict1 = {} is an empty dictionary.
7. Dictionary has no index
```# give an example
# Normal use
dict1 = {'name': 'David', 'Skill': 'Python', 'Age': '27', 'Gender': 'Male'}
# dict()
dict2 = dict(name='David', Skill='Python', Age='27', Gender='Male')
# Binary sequence
dict3 = dict([('name', 'David'), ('Skill', 'Python'), ('Age', '27'), ('Gender', 'Male')])
print('\n', dict1, '\n', dict2, '\n', dict3)
```

Run get ## 2.1 addition, deletion, modification and query of dictionary

commandmeaning
len()Length display
dict.get()Value
dict[]Value
dict[]=replace
del dict[]Specify delete
dict.popitem()Delete last item by default
dict.pop()Specify delete

For example, precautions:

```dict1 = {'name': 'David', 'Skill': 'Python', 'Age': '27', 'Gender': 'Male'}
print(len(dict1)) # Length display, statistics by item
print(dict1.get('name'),dict1['name']) # Two Key based methods
print(dict1.get('sex')) # No error is reported and no sex item is displayed
# print(dict1['sex']) # An error is reported because there is no sex item in the dictionary
dict1['Age'] = 18 # If there is a current Key, replace it
dict1['Hobby'] = 'hiking' # No current Key, add new item
print(dict1)
dict2 = {'1' : 1, '2' : 2, '3' : 3}
print(dict1)
del dict1['Age'] # Specified Key deletion
dict1.popitem() # Delete the last item by default
print(dict1)
print(dict1.pop('name')) # Specifies to delete. If there is a Key, the corresponding Value will be returned
print(dict1.pop('4', 4)) # Specifies to delete. If there is no Key, the specified Value 4 is returned
```

Obtained by operation ## 2.2 deep copy and light copy

1. copy.copy() shallow copy -- does not copy the second level data -- that is, nested data types
```import copy
dict1 = {'name':123, 'date':[1, 2, 3]}
dict2 = copy.copy(dict1)
```
1. copy. Deep copy -- copy all data

Summary:

1. Shallow copy only creates surface data, so the internal data id is the same; The deep copy is completely recreated, and the internal id has also changed.
2. Immutable data type - value changes, id changes; Value remains unchanged and id remains unchanged.
Variable data types - IDs are always different.

## 2.3 traversal dictionary

1. Key traversal expression: keys()
Statement: for k in dict.keys():
2. Value traversal expression: values()
Statement: for v in dict.values():
3. Item traversal expression: items()
Statement: for k,v in dict.items():

# 3 set

The overall features are similar to the list, so this content focuses on the comparison of different points

1. Only immutable data objects can be stored
2. Storage objects are unordered -- indexes are not supported
3. No repetition - de duplication
4. set type: set
5. Symbol: {}
6. Empty set establishment: set1 = set()

## 3.1 collective use

commandmeaning
inInclude in collection
not inIs it not included in the collection
set.pop()Delete the first data from by default
set.remove()Specify element deletion
set.clear()Empty collection

## 3.2 set operation

Symbolmeaning
&intersection
|Union
-Difference set
^Or set
<=Is it a subset
<Is it a true subset
>=Is it a superset
>Is it a true superset

# After class practice ```# Q1
a = {'name':'123', 'data':{'result':[{'src':'python1'}, {'src':'python2'},{'src':'python3'}]}}
b = a.get('data')
print(b)
c = b.get('result')
print(c)
print(c.get('src'), c.get('src'), c.get('src'))

# Q2
a = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
Key1 = []
Key2 = []
for b in a:
if b > 66:
Key1.append(b)
elif b < 66:
Key2.append(b)
else:
continue
set1 = {'Greater than 66':Key1, 'Less than 66':Key2}
print(set1)
```

obtain: Topics: Python list