![]() |
In Python, there is a powerful data structure called set(), which is an unordered collection of unique elements. In this article, we will learn how to add a dictionary to a set() using the union method. This can be particularly useful when you want to combine unique key-value pairs from different dictionaries into a single set. Before we dive into adding a dictionary to a set, let’s briefly understand the two main concepts involved:
Add A Dictionary To A Set() With UnionTo add a dictionary to a set() using the union() function, follow the steps below in Python. Step 1: Creating a Set and a DictionaryLet’s start by creating a set and a dictionary to work within our example: # set my_set = {1, 2, 3, 4, 5} # dictionary my_dict = {'a': 10, 'b': 20, 'c': 30} Step 2: Using union to Add a Dictionary to a SetNow, let’s add the key-value pairs from the dictionary to the set using the union method. In this example, my_dict.items() returns a view of the dictionary’s key-value pairs. By applying union(), we combine the set and the dictionary items, ensuring that only unique key-value pairs are added to the set. Python3
Step 3: Viewing the ResultLet’s print the updated set to see the result: Python3
Code ExamplesExample 1: Generally Used Method In this example, code initializes a set, `my_set`, with integers 1 to 5. A dictionary, `my_dict`, is created with key-value pairs. The `union` method combines `my_set` with the set of tuples obtained from `my_dict.items()`, and the updated set is printed. Python3
Output
{1, 2, 3, 4, 5, ('a', 10), ('c', 30), ('b', 20)} Example 2: Using the Curly Breackets In this example, the code creates a set `my_set` with integers 1, 2, and 3. A dictionary `my_dict` is converted to a set of tuples. The `union` method merges this set with the original, updating `my_set`, which is then printed. Note: Replace `{my_set}` with `print(my_set)` for correct representation. Python3
Output
Set after adding the dictionary: {1, 2, 3, ('b', 5), ('a', 4), ('c', 6)} ConclusionAdding a dictionary to a set() in Python using the union method is a simple yet powerful technique to merge unique elements from different data structures. This can be handy in scenarios where you want to maintain a collection of unique key-value pairs for various purposes in your Python programs. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |