Python dictionary and collection operation guide: creating, obtaining values, modifying and deleting key-value pairs, full analysis of copying and traversing methods

Article directory

  • Dictionary
    • Create dictionary
    • Get the value in the dictionary
    • Modify dictionary
    • Delete key-value pairs from dictionary
    • copy dictionary
    • dictionary comprehension
    • Traverse dictionary
      • Use keys() method
      • Use the values() method
      • Use items() method
    • summary
  • set
    • Create a collection
    • Set operations
    • Set operations
    • summary
  • Recommended Python boutique columns
    • Basic knowledge of python (0 basic introduction)
    • python crawler knowledge

Dictionary (dict)

Dictionaries are a new data structure called mapping. It is similar to a list and is used to store objects. However, dictionaries perform better when querying data than lists. This is because in the dictionary, each element has a unique name, and the specified element can be quickly found through this name.

A dictionary is composed of multiple key-value pairs, each of which has a unique key and corresponding value. The corresponding value can be quickly queried through the key. A dictionary is created using curly braces {} and providing key-value pairs. The key can be any immutable object (such as int, str, bool, tuple, etc.), but usually we use strings as keys.

Create dictionary

Use {} to create a dictionary, syntax: {k1:v1,k2:v2,k3:v3}.

# Use {}
d = {<!-- -->'name':'Sun Wukong', 'age':18, 'gender':'male'}

You can also use the dict() function to create a dictionary. Each parameter is a key-value pair. The parameter name is the key and the parameter value is the value. (In the dictionary created in this way, the keys are all strings. ).

# Use the dict() function to create a dictionary
d = dict(name='Sun Wukong', age=18, gender='male')

You can also convert a sequence containing a binary subsequence into a dictionary. A binary sequence refers to a sequence with only two values, such as [1,2], ('a', 3) and 'ab', etc. Subsequence refers to the situation where the elements in the sequence are also sequences, such as [(1,2),(3,5)].

d = dict([('name', 'Sun Wufan'), ('age', 18)])

Get the value in the dictionary

You can use keys to get values in the dictionary, the syntax is: d[key]. If the key does not exist, an exception KeyError will be thrown.

print(d['age'])

You can use the get(key[, default]) method to get the value in the dictionary based on the key. If the key does not exist in the dictionary, None will be returned. You can also specify a default value as the second parameter and return the default value when the value cannot be obtained.

print(d.get('name'))
print(d.get('hello', 'default value'))

Modify dictionary

You can use d[key] = value to modify the key-value pairs in the dictionary. If the key exists, its corresponding value will be overwritten; if the key does not exist, a new key-value pair will be added.

d['name'] = 'sunwukong' # Modify the key-value of the dictionary
d['address'] = 'Huaguoshan' # Add key-value to the dictionary

In addition, you can also use the setdefault(key[, default]) method to add key-value pairs to the dictionary. If the key already exists in the dictionary, the value corresponding to the key is returned and no operation is performed on the dictionary; if the key does not exist, the key is added to the dictionary and the corresponding value is set.

result = d.setdefault('name', 'Zhu Bajie')
result = d.setdefault('hello', 'Zhu Bajie')

You can also use the update([other]) method to add key-value pairs from other dictionaries to the current dictionary. If there are duplicate keys, subsequent key-value pairs will replace the current ones.

d = {<!-- -->'a': 1, 'b': 2, 'c': 3}
d2 = {<!-- -->'d': 4, 'e': 5, 'f': 6, 'a': 7}
d.update(d2)

Delete key-value pairs in the dictionary

You can use the del keyword to delete key-value pairs in the dictionary.

del d['a']
del d['b']

You can also use the popitem() method to randomly delete a key-value pair in the dictionary. Generally, the last key-value pair will be deleted. After deletion, this method will return the deleted key-value pair as a return value. The return value is a tuple containing two elements. The first element is the deleted key, and the second element is the deleted value.

result = d.popitem()

In addition, you can also use the pop(key[, default]) method to delete key-value pairs in the dictionary based on keys. This method returns the deleted value. If you delete a key that does not exist, an exception will be thrown. If a default value is specified and the deleted key does not exist, no error will be reported, but the default value will be returned directly.

result = d.pop('d')
result = d.pop('z', 'This is the default value')

In addition, you can use the clear() method to clear the key-value pairs in the dictionary.

d.clear()

Copy dictionary

You can use the copy() method to make a shallow copy of the dictionary. The copied object is independent of the original object, and modification of one will not affect the other. It should be noted that shallow copy will only copy the value inside the object. If the value is also a mutable object, they will not be copied.

d = {<!-- -->'a': 1, 'b': 2, 'c': 3}
d2 = d.copy()
d = {<!-- -->'a': {<!-- -->'name': 'Sun Wukong', 'age': 18}, 'b': 2, 'c': 3}
d2 = d.copy()
d2['a']['name'] = 'Zhu Bajie'
print('d =', d, id(d))
print('d2 =', d2, id(d2))

Dictionary derivation

Similar to list comprehensions, Python also supports creating dictionaries using dictionary comprehensions.

# Create a dictionary containing numbers
d = {<!-- -->i: i**2 for i in range(5)}
print(d) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Traverse the dictionary

Traversing a dictionary means accessing each key-value pair in the dictionary in sequence. In Python, there are several ways to implement dictionary traversal operations.

Use keys() method

The keys() method returns all keys of the dictionary. We can get each key-value pair in the dictionary by iterating over the keys.

Sample code:

d = {<!-- -->'name':'Sun Wukong','age':18,'gender':'male'}

for k in d.keys():
    print(k, d[k])

Use the keys() method to get all the keys in the dictionary, and then get the value of each key-value pair by iterating over the keys.

Use values() method

The values() method returns all values in the dictionary. We can get each key-value pair in the dictionary by iterating over the values.

Sample code:

d = {<!-- -->'name':'Sun Wukong','age':18,'gender':'male'}

for v in d.values():
    print(v)

Use the values() method to get all the values in the dictionary, and then access the value of each key-value pair by iterating over the values.

Use items() method

The items() method returns all items in the dictionary, each item is a two-valued subsequence containing the key and value.

Sample code:

d = {<!-- -->'name':'Sun Wukong','age':18,'gender':'male'}

for k, v in d.items():
    print(k, '=', v)

Use the items() method to get all the items in the dictionary, and then iterate over the items to get the key and value of each key-value pair.

Summary

A dictionary is a very flexible data structure that can be used to store various types of data. Through key-value pairs, we can quickly find, add, modify and delete elements. In addition, the dictionary also supports advanced usage such as dictionary derivation, which can help us operate data more conveniently. At the same time, you can choose the appropriate method to traverse the dictionary according to specific needs.

Set

Sets and lists are very similar, with the following differences:

  1. Only immutable objects can be stored in collections
  2. The objects stored in the collection are unordered and are not stored in the order in which elements are inserted.
  3. There cannot be duplicate elements in the collection

Create a collection

Collections can be created using {}:

s = {<!-- -->10, 3, 5, 1, 2, 1, 2, 3, 1, 1, 1, 1} # <class 'set'>

Note that collections cannot contain mutable objects, such as lists:

# s = {[1, 2, 3], [4, 6, 7]} # TypeError: unhashable type: 'list'

Sets can be created using the set() function:

s = set() # Empty set

Sequences and dictionaries can also be converted into sets via set():

s = set([1, 2, 3, 4, 5, 1, 1, 2, 3, 4, 5])
s = set('hello')
s = set({<!-- -->'a': 1, 'b': 2, 'c': 3}) # Only include keys in the dictionary

Collection operations

Collections can be processed using the following operations:

  • Use in and not in to check whether an element in a collection exists
  • Use len() to get the number of elements in a collection
  • Add elements to a collection using add()
  • Use update() to add elements from a collection to the current collection
  • Use pop() to randomly remove and return elements from a collection
  • Use remove() to delete the specified element in the collection
  • Use clear() to clear the collection
  • Shallow copy using copy()

Sample code:

s = {<!-- -->'a', 'b', 1, 2, 3, 1}

print('c' in s) # False
print(len(s))

s.add(10)
s.add(30)

s2 = set('hello')
s.update(s2)
s.update((10, 20, 30, 40, 50))
s.update({<!-- -->10: 'ab', 20: 'bc', 100: 'cd', 1000: 'ef'})

result = s.pop()

s.remove(100)
s.remove(1000)

s.clear()

print(result)
print(s, type(s))

Set operations

When operating on a set, the original set will not be affected, but an operation result will be returned.

Sample code:

s = {<!-- -->1, 2, 3, 4, 5}
s2 = {<!-- -->3, 4, 5, 6, 7}

result = s & amp; s2 # Intersection operation
result = s | s2 # Union operation
result = s - s2 # Difference set
result = s ^ s2 # XOR set

a = {<!-- -->1, 2, 3}
b = {<!-- -->1, 2, 3, 4, 5}

result = a <= b # Check if one set is a subset of another set
result = {<!-- -->1, 2, 3} <= {<!-- -->1, 2, 3} # True
result = {<!-- -->1, 2, 3, 4, 5} <= {<!-- -->1, 2, 3} # False

result = {<!-- -->1, 2, 3} < {<!-- -->1, 2, 3} # Check whether one set is a true subset of another set
result = {<!-- -->1, 2, 3} < {<!-- -->1, 2, 3, 4, 5} # True

result = a >= b # Check if one set is a superset of another
result = a > b # Check if one set is a true superset of another

print('result =', result)

The above are some basic operations and operations on collections, summarized as follows.

Summary

When using collections, you need to pay attention to the following points:

  1. A set is an unordered data structure with unique elements.
  2. Sets can be created using the {} or set() functions.
  3. Collections can only store immutable objects and cannot contain mutable objects.
  4. You can use in and not in to check whether an element in the collection exists.
  5. Use len() to get the number of elements in a collection.
  6. Use add() to add elements to a collection, and use update() to add elements from a collection to the current collection.
  7. Use pop() to randomly delete and return elements in a collection, use remove() to delete specified elements in the collection, and use clear() Clear the collection.
  8. Use copy() to make a shallow copy.
  9. Sets can perform intersection operations ( & amp;), union operations (|), difference operations (-) and XOR set operations (^).
  10. You can use <=, <, >= and > to compare the relationship between two sets, such as subsets , superset and proper subset, etc.

To sum up, a set is a very useful data structure suitable for scenarios where you need to store a set of elements and perform fast element lookup and deduplication.

Python boutique column recommendations

Basic knowledge of python (0 basic introduction)

[Basic knowledge of python] 0.print() function
[Basic knowledge of python] 1. Data types, data applications, data conversion
[Basic knowledge of python] 2.if conditional judgment and conditional nesting
[Basic knowledge of python] 3.input() function
[Basic knowledge of python] 4. Lists and dictionaries
[Basic knowledge of python] 5. for loop and while loop
[Basic knowledge of python] 6. Boolean values and four statements (break, continue, pass, else)
[Basic knowledge of python] 7. Practical operation-Using Python to implement the "Text PK" game (1)
[Basic knowledge of python] 7. Practical operation-Using Python to implement the "Text PK" game (2)
[Basic Knowledge of Python] 8. Programming Thinking: How to Solve Problems - Thinking
[Basic knowledge of python] 9. Definition and calling of functions
[Basic knowledge of python] 10. Writing programs with functions - Practical operation
[Basic knowledge of python] 10. Use Python to implement the rock-paper-scissors game-Function Practical Operation
[Basic knowledge of python] 11. How to debug - Common error reasons and troubleshooting ideas - Thinking
[Basic knowledge of python] 12. Classes and objects (1)
[Basic knowledge of python] 12. Classes and objects (2)
[Basic knowledge of python] 13. Classes and objects (3)
[Basic Knowledge of Python] 13. Classes and Objects (4)
[Basic knowledge of python] 14. Construction of library management system (practical operation of classes and objects)
[Python basics] 15. Coding basics
[Basic knowledge of python] 16. Basics and operations of file reading and writing
[Basic Knowledge of Python] 16. Python Implementation of "Ancient Poetry Dictation Questions" (File Reading, Writing and Coding - Practical Operation)
[Basic knowledge of python] 17. The concept of modules and how to introduce them
[Basic knowledge of python] 18. Practical operation-using python to automatically send mass emails
[Basic knowledge of python] 19. Product thinking and the use of flow charts - Thinking
[Basic Knowledge of Python] 20. Python Implementation of "What to Eat for Lunch" (Product Thinking - Practical Operation)
[Basic knowledge of python] 21. The correct way to open efficiently and lazily - graduation chapter
[Python file processing] Reading, processing and writing of CSV files
[python file processing] Excel automatic processing (using openpyxl)
[python file processing]-excel format processing

Python crawler knowledge

[python crawler] 1. Basic knowledge of crawlers
[python crawler] 2. Basic knowledge of web pages
[python crawler] 3. First experience with crawlers (BeautifulSoup analysis)
[python crawler] 4. Practical crawler operation (dish crawling)
[python crawler] 5. Practical crawler operation (lyrics crawling)
[python crawler] 6. Practical crawler operation (requesting data with parameters)
[python crawler] 7. Where is the crawled data stored?
[python crawler] 8. Review the past and learn the new
[python crawler] 9. Log in with cookies (cookies)
[python crawler] 10. Command the browser to work automatically (selenium)
[python crawler] 11. Let the crawler report to you on time
[python crawler] 12. Build your crawler army
[python crawler] 13. What to eat without getting fat (crawler practical exercise)
[python crawler] 14. Scrapy framework explanation
[python crawler] 15.Scrapy framework practice (crawling popular positions)
[python crawler] 16. Summary and review of crawler knowledge points