Home > Backend Development > PHP Tutorial > Deduplicate PHP array and return new dictionary using Python

Deduplicate PHP array and return new dictionary using Python

WBOY
Release: 2024-04-28 21:06:01
Original
763 people have browsed it

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.

使用 Python 去重 PHP 数组并返回新字典

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)
Copy after login

Output:

{'{"name": "John", "age": 30}': {'name': 'John', 'age': 30}, '{"name": "Jane", "age": 25}': {'name': 'Jane', 'age': 25}}
Copy after login

In this example:

  1. We use json.loads() from Load a PHP array into a JSON string.
  2. We use Python's 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.
  3. We then use dictionary comprehension to convert the set into a dictionary.
  4. Finally, we print the new dictionary after deduplication.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template