Working with dictionaries. Built-in functions list(), zip(). Dictionary bypass. Dictionary generators. Sorting. Combination of dictionaries with sets
Contents
- 1. Built-in list() function. Example of using with dictionaries
- 2. Built-in zip() function. Example of creation a dictionary
- 3. Bypassing the dictionary using for loop. Example
- 4. Using dictionaries for sparse data structures. Example
- 5. Creating dictionaries using dictionary generators. Examples
- 6. Sorting in dictionary by keys. Example
- 7. An example of using dictionary key lists in set operations
- Related topics
Search other websites:
1. Built-in list() function. Example of using with dictionaries
Using the built-in list() function allows you to get lists of values, keys and pairs (key: value). To create an appropriate list using list() you need to use one of the following methods:
- the values() method allows you to get a list of dictionary values;
- the keys() method allows you to get a list of dictionary keys;
- the items() method allows you to get a list of pairs (key:value).
More details about using the values(), keys(), items() methods are described here.
Example.
# Work with dictionaries # Built-in list() method # Source dictionary Figures = { 1:'Rectangle', 2:'Triangle', 3:'Circle' } # 1. Get a list of dictionary values values = list(Figures.values()) print(values) # ['Rectangle', 'Triangle', 'Circle'] # 2. Get a list of dictionary keys keys = list(Figures.keys()) # keys = [1, 2, 3, 4] print(keys) # 3. Get a list of pairs (key:value) pairs = list(Figures.items()) print(pairs) # [(1,'Rectangle'),(2,'Triangle'),(3,'Circle')]
⇑
2. Built-in zip() function. Example of creation a dictionary
The zip() function allows you to create a dictionary by combining lists of keys and values.
Example.
# Dictionaries. Function zip() # Creating a dictionary from lists of keys and values Numbers = dict(zip([1, 2, 3], ['One', 'Two', 'Three'])) print(Numbers) # {1: 'One', 2: 'Two', 3: 'Three'}
⇑
3. Bypassing the dictionary using for loop. Example
The example demonstrates bypassing a dictionary using a for loop and displaying all pairs (key: value).
Example.
# Work with dictionaries # Bypassing the dictionary using a for loop # Source dictionary Months = { 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec' } # The loop for of bypass the dictionary # in loop: mn - key, Months[mn] - value for mn in Months: print(mn, ': ', Months[mn])
The result of the program
1 : Jan 2 : Feb 3 : Mar 4 : Apr 5 : May 6 : Jun 7 : Jul 8 : Aug 9 : Sep 10 : Oct 11 : Nov 12 : Dec
⇑
4. Using dictionaries for sparse data structures. Example
Dictionaries can be used effectively to represent sparse data structures. Two-dimensional arrays in which only a few elements have certain values can be examples of such data.
Example. The example demonstrates the representation of a sparse matrix of numbers in the form of a dictionary. Let a matrix be given
which must be presented in the form of a dictionary. The solution to the problem is as follows:
# Dictionaries. Representation of sparse data structures # Matrix M M = {} # create an empty dictionary M[(0, 1)] = 1 # key=(0,1): value=1 M[(1, 2)] = 3 # pair (key:value) = ((1,2):3) M[(2, 0)] = 2 # pair (key:value) = ((2,0):2) print(M) # {(0, 1): 1, (1, 2): 3, (2, 0): 2}
In the above example, dictionary keys are tuples that contain the coordinates of non-empty elements. So, the key value (2, 0) means row 2, column 0.
⇑
5. Creating dictionaries using dictionary generators. Examples
Dictionaries can be created using dictionary generators. In this case, one of the following methods is used:
- generate a dictionary based on a given expression;
- generate a dictionary based on an iterated object;
- initialize the dictionary from key lists;
- generate a dictionary using the zip() function.
The example demonstrates the use of all methods.
Example.
# Dictionaries. Dictionary generators # 1. Generate a dictionary based on a given expression # Pairs are generated (key: value) = (i: 5*i) A = { i: i*5 for i in [10,20,30,40] } print(A) # {10: 50, 20: 100, 30: 150, 40: 200} # 2. Generate a dictionary by an iterable object (string) s = 'Hello' B = { sym: sym*3 for sym in s } # пара (sym:sym*3) print(B) # {'H': 'HHH', 'e': 'eee', 'l': 'lll', 'o': 'ooo'} numbers = [ 15, 25, 30 ] C = { num: str(num) for num in numbers } print(C) # {15: '15', 25: '25', 30: '30'} # 3. Initializing a Dictionary from a Key List. # Fill the list of keys with the value # entered from the keyboard value = int(input('Input value: ')) listKeys = [ 1, 2, 3, 4 ] D = { lk:value for lk in listKeys } print(D) # Fill key list with None value value = None listKeys = [ 'a', 'b', 'c' ] E = { lk:value for lk in listKeys } print(E) # {'a': None, 'b': None, 'c': None} # 4. Generate a dictionary using the zip() function WMonths = [ 'Dec', 'Jan', 'Feb'] NumMonths = [ 12, 1, 2 ] F = { nm:wm for (nm,wm) in zip(NumMonths,WMonths) } print(F) # {12: 'Dec', 1: 'Jan', 2: 'Feb'}
⇑
6. Sorting in dictionary by keys. Example
As you know, the keys in the dictionary are stored in random order. If it becomes necessary to sort the dictionary by keys, then you can use the sort() method, which is used for lists. To do this, you first need to convert the representation of the keys into a list.
Example.
# Dictionaries. Sorting by keys # Source dictionary A = { 'f':10, 'а':2, 'с':17 } # Sorting by keys # 1. Get a keys view ak = A.keys() # ak = dict_keys(['f', 'а', 'с']) # 2. Convert ak to list list_ak = list(ak) # list_ak = ['f', 'а', 'с'] # 3. Sort a list of keys - sort() function list_ak.sort() # ['а', 'с', 'f'] # 4. Print the list of (key: value) # in sorted order by keys, # form a new dictionary B = {} for k in list_ak: print('(', k, ': ', A[k], ')') B[k] = A[k] print(B) # {'a': 2, 'c': 17, 'f': 10}
⇑
7. An example of using dictionary key lists in set operations
Based on the keys of the dictionary, you can create lists. These key lists can be used in operations on sets that form a new set. In other words, you can mix different mapping objects (sets, dictionaries) with each other using the appropriate operations.
In order for the keys to be used in operations on sets, you must first convert them to lists using the keys() method. More details about using the keys() method are described here.
Example. The example demonstrates the interaction of dictionaries and sets using operations on the sets |, &, ^.
# Dictionaries. Combining dictionaries and sets # Source dictionary A = { 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five' } # Combining key mapping and sets, # we get a new set # 1. Get key mapping keys = A.keys() # keys = dict_keys([1, 2, 3, 4, 5]) # 2. Generate a new set of keys that contains the number 2 B = keys & {2} # B = {2} - a new set # 3. Generate a new set of keys that contains the numbers 3, 5 C = keys {3, 5} # {1, 2, 4} # 4. Add the numbers 8, 11 to the set of keys D = keys | { 8, 11 } # D = {1, 2, 3, 4, 5, 8, 11}
⇑
Related topics
- Dictionaries. Basic concepts. Specifications. Creating dictionaries. Accessing dictionary values
- Build-in functions and dictionary processing operations
- Methods of working with dictionaries
⇑