# Generators of sets. Dictionary generators. Sets and generator expressions. Dictionaries and generator expressions. Examples

Before exploring this topic, it is recommended that you familiarize yourself with the following topic:

##### 1. Generators of sets. Concepts. General form

In addition to list generators, there are also set generators and dictionary generators in Python. These new forms of generators were introduced in Python 3.0. Set generators allow you to get sets based on a given expression formed from a sequence.

The general form of using the set generator is as follows:

resSet = { f(x) for x in sequence if condition(x) }

here

- resSet – the resulting set;
- f(x) – arbitrary expression;
- x – a variable that alternately takes a value from sequence;
- sequence – some sequence of values;
- condition(x) – the condition applied to the variable
**x**.

There is also a simplified general form of a set generator. There is no if condition in this form:

{ f(x) for x in sequence }

Both of the above forms give the result entirely in the form of a set. These forms can be replaced accordingly by constructions

resSet = set ( f(x) for x in sequence if condition(x) )

or

resSet = set ( f(x) for x in sequence )

##### 2. Examples of using set generators

##### 2.1. Generating a set of random numbers according to a condition

**Task****. **Use the set generator to form a set of numbers that are raised to power 3.

**Solution****.**

# Generator set # Form a set of 10 numbers raised to power 3 res = { x*x*x for x in range(1, 11) } print("res = ", res)

Program result

res = {64, 1, 512, 8, 1000, 343, 216, 729, 27, 125}

##### 2.2. Generate set based on the given list

**Task****.** A list L is given. Using the set generator, it is necessary to create a set S based on the list L.

# Set generator. # Form the set from the given list L = [ 2.88, 3.5, 1.7, -2.4, 65.8, 2.88, 2.88, 1.7, -2.4, 3.2 ] S = { item for item in L } print("S = ", S)

Program result

S = {3.5, 65.8, -2.4, 2.88, 1.7, 3.2}

##### 2.3. Generate a set of paired items from the list

**Task****.** Задан список целых чисел. С помощью генератора множеств образовать множество, содержащее парные элементы списка.

**Solution****.**

# Set generator. # From the given list, form a set containing paired elements L = [ 2, 8, 5, 2, 8, 4, 3, 3, 2, 8, 6, 7, 11, 2 ] S = { item for item in L if item%2 == 0 } print("S = ", S)

Program result

S = {8, 2, 4, 6}

##### 3. Dictionary generators. Peculiarities. General form

Dictionary generators have been introduced in Python since version 3.0. With the help of these generators, dictionaries can be formed according to the following general form

resDict = { key:val for (key, val) in zip(keys, vals) if condition }

here

- resDict – an object that is a dictionary;
- (key:val) – a pair in which key is a key, val is the value obtained by the key;
- sequence – some sequence. This sequence can be formed by the zip() function or another function;
- condition – the condition on the basis of which the values from the sequence are selected.

The above general form can be simplified in that the if condition is missing

resDict = { key:val for (key, val) in zip(keys, vals) }

Using the dict() function, you can replace both common forms with the following calls

resDict = dict(zip(keys, values))

here

- keys – a set of keys in the dictionary;
- values – a set of values corresponding to keys.

##### 4. Examples of creating dictionaries based on dictionary generators

##### 4.1. Generate a dictionary based on a range of values range()

**Task****.** A sequence of paired numbers from 0 to 10 inclusive is given. From the given sequence, form a dictionary containing (key:value) pairs in which the value of key is twice of value.

**Solution****.**

# Dictionary generators # Create a dictionary based on a range of values # Specify a set of paired numbers 0, 2, 4, 8, 10 R = range(0, 11, 2) # Create a dictionary D = { t: t+t for t in R } # Print the result print(D)

Program result

{0: 0, 2: 4, 4: 8, 6: 12, 8: 16, 10: 20}

##### 4.2. Build a dictionary based on a list of numbers

**Task****.** Based on the list of Values numbers, form a dictionary in which each key is the position number of a value from the Values list. In other words, enumerate the Values value. Consider that positions are numbered from 1.

**Solution****.** To get the dictionary, you need to use the zip() function, which combines the two sequences Keys and Values.

# Dictionary generators # Task. Number the values in the list # A list of numbers is specified - these will be values Values = [ 1.7, 2.2, 0.4, 3.8, 2.2 ] # Generate keys keys based on the list Keys = range(1, len(Values)) # Way 1. Create a dictionary and output it D = { key:val for (key, val) in zip(Keys, Values) } print(D) # Way 2. Using the dict() function D2 = dict(zip(Keys, Values)) print(D2)

Program result

{1: 1.7, 2: 2.2, 3: 0.4, 4: 3.8} {1: 1.7, 2: 2.2, 3: 0.4, 4: 3.8}

##### 4.3. Generate a dictionary based on a list of strings in which the length is greater than the specified value

**Task****.** A list S of strings is given. Based on the list S, form a dictionary D, in which the keys are the position of the corresponding string in the list. Include in the dictionary only those elements from the list S, the length of which is more than 4 characters.

**Solution****.**

# Task. Include strings longer than 4 characters in the dictionary. # A list of strings is specified S = [ 'abc', 'ab', 'abcd', 'jklmn', 'jprst', 'xyz' ] # Form a new list with strings longer than 4 S2 = [ t for t in S if len(t)>4 ] # Create a list of line numbers according to a condition L = range(1, len(S2)+1) # Create a dictionary D = { k:v for (k, v) in zip(L, S2) } # Display the dictionary print(D)

Program result

{1: 'jklmn', 2: 'jprst'}

##### 4.4. Build a dictionary based on the set of unique strings. Dictionary values are string lengths

**Task****.** A set S of strings is given. Based on the set S, form a dictionary D in which:

- keys are strings from the set S;
- values are the length of each string, respectively.

**Solution****. **

# A set of lines is given S = { 'abc', 'ab', 'abcd', 'jklmn', 'jprst', 'xyz' } # Based on the set S, generate a value using a list generator. # Each value is the length of the corresponding string in the set S L = [ len(t) for t in S ] # Way 1. Create a dictionary and output it D = { k:v for (k, v) in zip(S, L) } print(D) # Way 2. Using the dict() function D2 = dict(zip(S, L)) print(D2)

Program result

{'abc': 3, 'ab': 2, 'abcd': 4, 'jklmn': 5, 'jprst': 5, 'xyz': 3} {'abc': 3, 'ab': 2, 'abcd': 4, 'jklmn': 5, 'jprst': 5, 'xyz': 3}

##### 4.5. Form a dictionary from a tuple of numbers, in which the values are positive

**Task****.** A tuple is given. Create a dictionary in which key:value pairs are formed according to the following rules:

- values are only positive numbers;
- the keys are the ordinal numbers of the corresponding values.

**Solution**

# Task. Build a dictionary based on a tuple # Specified tuple T = ( -8.2, 3.4, 1.6, 12, 12.5, -4.2, 0.8, 7, 7 ) # Form a dictionary D = { key:value for (key, value) in zip(range(1, len(T)+1), T) if value>0 } # Print the dictionary print(D)

Program result

{2: 3.4, 3: 1.6, 4: 12, 5: 12.5, 7: 0.8, 8: 7, 9: 7}

##### 5. Sets, dictionaries, and generator expressions

Set generators and dictionary generators construct the entire result. If you need values from a set or a dictionary to be supplied one at a time on demand, then the forming expression must be enclosed in parentheses ( ).

Using a generator expression to supply data to a set is implemented as follows

IterObjSet = (expression) S = set(IterObjSet)

here

- expression – generator expression;
- IterObjSet – an iterated object that supplies data on demand;
- S – resulting set.

Using a generator expression to supply data to a dictionary could be like this

IterObjDict = (expression) D = dict(IterObjDict) D = { key:value for (key, value) in zip( Keys, Values) }

If you use an iterated object to generate a dictionary using a generator, then the following code is possible

D = { key:value for (key, value) in zip( Keys(IterObjDict), Values(IterObjDict)) }

here

- key:value – a pair of values obtained according to the Keys and Values sequences;
- Keys(IterObjDict) – a sequence of keys that can be obtained from IterObjDict. A situation is possible when the sequence of Keys keys is formed independently of IterObjDict;
- Values(IterObjDict) – a sequence of values that can be obtained from IterObjDict. It is possible that the sequence of Values is generated regardless of IterObjDict;
- D – resulting dictionary.

##### 6. An example demonstrating the use of generator expressions in combination with sets

The example demonstratively creates a list of L integer elements. Then, based on the list L, an iterated IterObj object is created that will supply data on demand. The object is created using a generator expression.

Using the next() method, the first 3 elements are retrieved from the iterated object and added to the set S. The remaining elements are added to the set S2.

# Sets and generator expressions # Specified list. L = [ 2, 8, 3, 4, 6, 1, 7, 9 ] # 1. Generate an iterated object containing elements from the list L IterObj = ( item for item in L ) # generator expression # 2. Form a set based on an iterated IterObj object # 2.1. Create the empty set S S = set() # 2.2. Pull out 3 elements one by one from IterObj # Pull first element from IterObj and add it to set S t = next(IterObj) S = S | {t}; # Add another element to the set S t = next(IterObj) S = S | {t}; # Add the third element to the set S t = next(IterObj) S = S | {t} # Display the set S print("S = ", S) # Display the elements that are left in IterObj S2 = set(IterObj) print("S2 = ", S2)

Program result

S = {8, 2, 3} S2 = {1, 4, 6, 7, 9}

##### 7. An example demonstrating the use of generator expressions to supply values to dictionaries

**Task****.** A list of strings L is given. Based on the list L, form a dictionary. In a dictionary, keys are the position numbers of the corresponding string, and the values are strings.

**Solution****.**

# Dictionaries and generator expressions # 1. A given list of strings L = [ 'abc', 'abcd', 'fgh', 'jklmn', 'wxy' ] # 2. Get the length of a list length = len(L) # 1. Generate an iterated object containing elements from the list L IterObj = ( item for item in L ) # вираз-генератор # 2. Form a dictionary containing the first 2 lines from the list L # 2.1. Form an empty dictionary D = {} # 2.2. Extract the first element from IterObj and add it to the dictionary t = next(IterObj) D[0] = t # here pair (key:value) => (0 : t) # 2.3. Pull out the second element from the IterObj t = next(IterObj) D[1] = t # (key:value) => (1 : t) # 2.4. Display dictionary D print(D) # 3. Form a second dictionary from the elements remaining in IterObj # 3.1. Get a range of keys R = range(2, length+1) # 3.2. Form dictionary D2 = { key:value for (key, value) in zip(range(2, length+1), IterObj) } # 3.3. Display the dictionary print(D2)

Program result

{0: 'abc', 1: 'abcd'} {2: 'fgh', 3: 'jklmn', 4: 'wxy'}

⇑