Python dictionary parsing (creating a dictionary using a list of tuples, creating a dictionary using keyword arguments, dict() function, del, clear(), keys(), values(), items(), get(), dictionary derivation)

Article directory

  • Python dictionary parsing
    • Python dictionary creation method
      • basic method
      • Use the built-in dict() function
        • Use a list of tuples
        • Use keyword arguments
    • Dictionary operations
      • Access dictionary elements
      • Modify dictionary
      • Delete dictionary elements, clear dictionary, delete dictionary (del, clear())
        • The difference between deleting a dictionary and clearing a dictionary
        • Clear the dictionary (clear())
        • Delete dictionary (del)
    • dictionary method
      • keys() (returns a view object containing all keys)
      • values() (returns a view object containing all values)
      • items() (returns a view object containing all (key, value) tuples)
      • get() (get the value based on the key, return the default value if the key does not exist)
    • Dictionary comprehension (quickly create dictionary)
    • Formatted printing of python dictionary and expanded printing (pprint.pprint())
    • Use dictionaries to solve real-world problems

Python dictionary parsing

Python dictionary is a built-in data type used to store key-value pairs. Dictionaries appear in many programming languages, such as objects in JavaScript or hash tables in Ruby.

Python dictionary creation method

Basic methods

Python dictionary is a mutable container model and can store any type of object. Each key-value pair of the dictionary is separated by a colon, each pair is separated by a comma, and the entire dictionary is enclosed in curly braces. Dictionary keys must be unique, but values do not.

An example of creating a simple dictionary is as follows:

nested_dict = {<!-- -->'info': {<!-- -->'name': 'John', 'age': 25, 'job ': 'Developer'}, 'skills': ['Python', 'Java', 'C++ ']}

You can also write the dictionary into multiple lines and clearly indicate the nesting level through indentation to increase readability:

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

Use the built-in dict() function

Using a list of tuples
# Tuple list
info_dict = dict([('name', 'John'), ('age', 25), ('job', 'Developer')])
skills_list = ['Python', 'Java', 'C++']
nested_dict = dict([('info', info_dict), ('skills', skills_list)])
Use keyword arguments
# Keyword parameters
info_dict = dict(name='John', age=25, job='Developer')
skills_list = ['Python', 'Java', 'C++']
nested_dict = dict(info=info_dict, skills=skills_list)

Dictionary operations

Access dictionary elements

Values in a dictionary can be obtained by key. If the key does not exist, Python raises a KeyError.

print(nested_dict['info']['name']) # Output: 'John'

Modify dictionary

Values in the dictionary can be modified directly by key.

nested_dict['info']['age'] = 28 # Modify the value of key 'age'

Delete dictionary elements, clear dictionary, delete dictionary (del, clear())

Use the del keyword to delete an entire dictionary or its elements. Use clear to clear the dictionary.

del nested_dict['info']['job'] # Delete key 'job'
nested_dict.clear() # Clear the dictionary
del nested_dict # Delete dictionary
The difference between deleting a dictionary and clearing a dictionary
Clear the dictionary (clear())

dict.clear(), removes all key-value pairs in the dictionary, but the dictionary itself still exists. If a variable refers to this dictionary, the variable will point to an empty dictionary.

dict1 = {<!-- -->'name': 'John', 'age': 25, 'job': 'Developer'}
dict1.clear()
print(dict1) # Output: {}
Delete dictionary (del)

del, which will destroy the dictionary object. Attempting to access a deleted dictionary results in NameError.

dict1 = {<!-- -->'name': 'John', 'age': 25, 'job': 'Developer'}
del dict1
print(dict1) # Raises NameError: name 'dict1' is not defined

Dictionary method

keys() (returns a view object containing all keys)

This method returns a view object containing all keys.

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

print(nested_dict.keys())
# dict_keys(['info', 'skills'])

values() (returns a view object containing all values)

This method returns a view object containing all values.

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

print(nested_dict.values())
# dict_values([{'name': 'John', 'age': 25, 'job': 'Developer'}, ['Python', 'Java' , 'C++ ']])

items() (returns a view object containing all (key, value) tuples)

This method returns a view object containing all (key, value) tuples.

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

print(nested_dict.items())
# dict_items([('info', {'name': 'John', 'age': 25, 'job': 'Developer'}), ('skills ', ['Python', 'Java', 'C++ '])])

get() (get the value according to the key, return the default value if the key does not exist)

This method accepts a key and a default value as parameters. If the key exists in the dictionary, it returns the value corresponding to the key, otherwise it returns the default value.

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

print(nested_dict.get('info', 'N/A').get('age', 'N/A'))
#25

print(nested_dict.get('info', 'N/A').get('sex', 'N/A'))
# N/A

Dictionary comprehension (quickly create dictionary)

Python dictionary comprehensions are a quick way to create a dictionary from one or more iterators. Similar to list comprehensions, but the result is a dictionary.

squares = {<!-- -->x: x*x for x in range(6)} # Create a dictionary with keys 0-5 and values squared

print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Formatted printing python dictionary, expanded printing (pprint.pprint())

The pprint() function of the pprint library can print python dictionaries in a relatively beautiful format:

import pprint

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

pprint.pprint(nested_dict)
# {'info': {'age': 25, 'job': 'Developer', 'name': 'John'},
# 'skills': ['Python', 'Java', 'C++ ']}

If you want each field of the dictionary to be fully expanded for printing, you can add the width parameter. This parameter determines the minimum line break threshold. For example, you can set width=1:

import pprint

nested_dict = {<!-- -->
    'info': {<!-- -->
        'name': 'John',
        'age': 25,
        'job': 'Developer'
    },
    'skills': ['Python', 'Java', 'C++']
}

pprint.pprint(nested_dict, width=1)
# {'info': {'age': 25,
# 'job': 'Developer',
# 'name': 'John'},
# 'skills': ['Python',
# 'Java',
# 'C + + ']}

Use dictionaries to solve practical problems

Dictionaries are widely used in solving practical problems. For example, dictionaries can be used to store and process large amounts of data. The key-value structure of a dictionary provides a flexible way to organize and process data.

Here is an example that shows how to use a dictionary to count the occurrences of each character in a string:

def count_chars(s):
    result = {<!-- -->}
    for char in s:
        if char in result:
            result[char] + = 1
        else:
            result[char] = 1
    return result

print(count_chars('hello world')) # Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

In the above example, the dictionary keys are characters and the values are the number of occurrences of that character in the string.