Steps to deduplicate PHP arrays in Python: Use json.loads() to load PHP arrays from JSON strings. Use set() to deduplicate the dictionaries in the array and use the hashes of the duplicate dictionaries as keys. Use dictionary comprehension to convert a set into a dictionary. Return the new dictionary after deduplication.
Using Python to deduplicate PHP arrays and return new dictionaries
When we get array data from a PHP application and want to When processing it in Python, you may encounter problems with duplicate data. To get clean and non-duplicate data, we can use Python tools to deduplicate the PHP array and return a new dictionary.
import json # 假设我们有一个 PHP 数组,可以通过以下方式获得 php_array = json.loads('[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}, {"name": "John", "age": 35}]') # 使用 set() 去重数组中的字典 unique_dict = {json.dumps(item): item for item in php_array} # 将 set 转换为字典 unique_dict = dict(unique_dict) # 打印去重后的新字典 print(unique_dict)
Output:
{'{"name": "John", "age": 30}': {'name': 'John', 'age': 30}, '{"name": "Jane", "age": 25}': {'name': 'Jane', 'age': 25}}
In this example:
json.loads()
from Load a PHP array into a JSON string. set()
data structure, which can automatically discard duplicate elements to create a collection of deduplicated dictionaries. json.dumps()
Function is used as a hash function for dictionary keys so that duplicate dictionaries will have the same keys. The above is the detailed content of Deduplicate PHP array and return new dictionary using Python. For more information, please follow other related articles on the PHP Chinese website!