Home > Backend Development > Python Tutorial > How Can I Implement an Ordered Set in Python?

How Can I Implement an Ordered Set in Python?

Barbara Streisand
Release: 2024-12-14 03:00:09
Original
198 people have browsed it

How Can I Implement an Ordered Set in Python?

Python Ordered Set

Python provides an ordered dictionary, but lacks an explicit ordered set. However, as of Python 3.7, the standard library's dict can be employed as an ordered set using only keys and discarding values.

Using dict as an Ordered Set

To emulate an ordered set using dict, simply create a dict with keys and set the values to None. To retrieve the ordered set, access the dict's keys().

keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']
ordered_set = list(dict.fromkeys(keywords))  # ['foo', 'bar', 'baz']
Copy after login

Pre-Python 3.7: Using collections.OrderedDict

For older Python versions, the collections.OrderedDict object is available for creating ordered sets.

from collections import OrderedDict

ordered_set = OrderedDict()
for keyword in keywords:
    ordered_set[keyword] = None
Copy after login

The above is the detailed content of How Can I Implement an Ordered Set in Python?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template