SoFunction
Updated on 2024-11-15

Python A look at Python collection and dictionary datatypes in one article

preamble

The set datatype is an unordered aggregation of simple objects, and the elements of a set are not repeated.Sets in Python include mutable set objects (set) and immutable set objects (frozenset). A dictionary is a data structure with key-value pairs. Each key cannot be duplicated, and a dictionary can be queried for values based on its keys. The appearance of these two good brothers are composed of the use of {} for wrapping. And the underlying principles have some commonality. Their underlying implementation is generally used in the hash table.

I. Collection types🪐

1. Definitions

  • Set data types are categorized into mutable sets (set) and immutable sets (frozenset).
  • Elements in a set are not repeatable and are unordered. (Because objects exist within collections are stored as hashed objects)
  • What is placed inside a set should be immutable objects (numeric data types, string tuples, immutable sets)
  • The representation of an empty set is set(). {} is the representation of the empty dictionary.
  • You can use in /not in to determine if an element is in the collection.

2. How the collection is used

Sets are used in a somewhat similar way to the sets you learned in middle school. That is to say, the mathematical operations of intersection, union, complement and difference of sets can be applied to Python sets. The representation is as follows

Suppose the set has four intersections A={1,2,3}, B={2,3,4}, C={3,4,5}, and D={1,2,3,4}:

A|B|C={3}

And:

A&B={1,2,3,4}

Complements:

A^D={4}

differ from

A-B={1}

You can use these methods to make judgments about whether there are the same elements and whether there is an inclusion relationship

3. Set derivatives

When we talked about lists earlier, we talked about list derivatives, which can directly generate a list of what you want. Today we will talk about the collection of list derivatives

Deductive Grammar:

{ variable generic for i in sequence [judgment condition]}

For example, the following formula finds the square of an even number

print({i*i for i in range(10) if i%2==0})

4. Variable sets

Variable sets are created with set (variable sets are still hash tables at the bottom, so they can only store immutable objects) print(set([1,2,3]))

The created object has a series of methods. add(x), remove(x), discard(x), pop(), clear() The above functions correspond to adding an element, removing an element (without throwing an exception), removing an element, randomly popping an element, and clearing the collection.

The actual code of operation:

'''
Set set, the bottom is still a hash table, unordered and unrepeatable.
'''
# Operations (add, delete, change, create collections)
# Mode of declaration I
s1={123,'hello',666,888,'Tom'}
# Mode of declaration II
s2=set({123,'hello',666,888,'Tom'})
# Collection generator
s3={i*i for i in range(10)}
print(s1,id(s1),type(s1))
print(s2,id(s2),type(s2))
print(s3)
# Determine if sets are the same (comparison is of elements contained within)
print(s1==s2)
print(s1==s3)

# Increase
# Suitable for adding one by one
(123123)
print(s1)
# Ideal for adding multiple elements
# Add the string directly
(['world','milk'])
(('world1','milk1'))
# Split the string and add it
('world3','milk3')
print(s1)

# Delete
# Delete the passed-in element, throw an exception if there is none.
# (777)
# Delete element, don't throw exception if none None
(888)
print((777))
print(s1)
# Remove an element at random (no parameter passing)
()
# Clear all elements
()
# Empty sets
print(s1)

'''Relationships between sets, intersection, concatenation, difference sets, subsets of concatenated difference sets, supersets, whether elements are the same'''
s4=set(s2)
s5=set(s2)
('joso')
('pink')
# whether s2 is a subset of s4
print((s4))
# Is s2 a superset of s4
print((s4))
# Are both sets and elements different
print((s4))

# Intersection
print('--------------------')
print((s2))
print(s4 & s2)
# And the concatenation
print('--------------------')
print((s5))
print(s4 | s5)
# Difference sets
print((s5))
print(s4-s5)
# Symmetric difference sets
print(s4.symmetric_difference(s5))
print(s4 ^ s5)

II. Dictionary types 🪐

1. Definitions

Dictionaries are mapping relationships between keys and values, so they are sometimes called mapped data types. Dictionary key is a hash data type (immutable), the value is an arbitrary type, and in a dictionary there can only be one of each type of key, the value can be duplicated can be arbitrary. You can get the corresponding value through the key.

The general form of a key-value pair is key:value

So the general form of a dictionary is {key1:value,key2:value,key3:value...}

Dictionaries can be created directly using literals {key1:value,key2:value,key3:value...} or using dict.

dict supports dictionary to dictionary and sequence to dictionary.

2. How dictionaries are used

Dictionary use can get keys, values and [key, value] lists separately

The way is:

  • () # Get the list of keys
  • () # Get the list of values
  • () # Get a list of keys and values in the form of a tuple

Dictionaries can use in / not in to determine if a key is contained within the dictionary.

Dictionary objects have a series of methods:

  • clear() #clear the element
  • copy() #Copy the dictionary
  • get(k) #Get the value based on the key
  • pop(k) #Delete the key if it exists and return the value, throw an exception if it doesn't.
  • pop(k,v)#delete and return value if key exists, return V if not
  • setdefault(k,v) #return the value of the k key if it exists, add the k key if it doesn't exist and assign None.
  • update() # Pass in a dictionary or key-value pair update operation

3. Dictionary derivatives

Dictionary derivatives are used in a similar way to list derivatives and set derivatives, except that they have two values {k:v for k in ...for v in ...}

{x:x*x for x in range(10) if x%2==0}
{x:y for x in range(10) for y in range(10,20)}

4. Code Exercise

'''
Comparative Learning What is the difference between a dictionary and a list?
A list is in square brackets. The data in a list is singular, ordered, and can be repeated.
Dictionaries are in square brackets The data in a dictionary is in pairs Unordered Key-value pairs can't be scrambled, and if a key is duplicated, the value is overwritten.

The data in the dictionary is not in order, the underlying principle is a hash table, using the hash table to realize the key-value correspondence
'''
# Dictionary Creation I
# When the same key in the dictionary corresponds to a different value, the previous value will be overwritten.
s={'name':'Zhang San','paassward':'888888','name':'Makabaka'}
# Dictionary creation II
ss=dict(user='pig',passward='123123')
# Dictionary creation method III (list creation)
t1=['username','passward']
t2=['Tom','1980']
# upper, lower is a function that takes all upper case and all lower case of a string.
sss={():() for t1,t2 in zip(t1,t2)}
# Print display dictionary type
print(s,type(s))
print(ss,type(s))
print(sss,type(s))
# Addition/modification of dictionary elements
# Since there can only be one of each key in the dictionary, overwriting occurs when a key corresponds to a new value.
    # That is, the value corresponding to the original key is modified
s['name']='Li Si'
print(s)
# Or use a key that wasn't there to create a new effect #
s['age']='20'
print(s)

# Get the dictionary value
# Get all keys
keyS=()
print(keyS)
# Get all values
valueS=()
print(keyS,valueS)
# Get all key-value pairs
iteM=()
print(iteM)
# Get value for key Dictionary name[key]----- not found will report error
print(s['paassward'])
# get value for key dictionary name.get()---- can't find it can specify what to print
print(('paassward'))
print(('qwe','Not found'))
# Determine if it's in a dictionary (both keys and values can be determined)
print('paassward' in s,'888888' in s)
# Dictionary element removal
del s['name']
print(s)
# Empty the dictionary
()
print(s)

# Dictionary traversal
# temp as a key within the dictionary, then look for the value within the dictionary
for temp in ss:
    print(temp,ss[temp],(temp))

summarize

Collections and dictionaries to this end, these two data types are relatively simple, but more built-in methods. Focus on mastering their characteristics: mutable immutable and so on. I believe we can play around with these two data types.

To this point this article on Python an article to understand the Python collection and dictionary data types of the article is introduced to this, more related Python collection content please search my previous articles or continue to browse the following related articles I hope you will support me in the future more!