-
Notifications
You must be signed in to change notification settings - Fork 5
/
fs_dict.Rmd
283 lines (225 loc) · 9.01 KB
/
fs_dict.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
---
title: "Python Dictionary Examples and Usages"
titleshort: "Python Dictionary Examples and Usages"
description: |
Generate a dictionary, loop through a dictionary.
List comprehension with dictionary.
core:
- package: py
code: |
dc = {'key': "name", 'val': 1}
update()
dc.items()
zip()
- package: copy
code: |
deepcopy
date: 2020-05-23
date_start: 2020-11-06
output:
pdf_document:
pandoc_args: '../../_output_kniti_pdf.yaml'
includes:
in_header: '../../preamble.tex'
html_document:
pandoc_args: '../../_output_kniti_html.yaml'
includes:
in_header: "../../hdga.html"
always_allow_html: true
urlcolor: blue
---
### Dictionary
```{r global_options, include = FALSE}
try(source("../../.Rprofile"))
```
`r text_shared_preamble_one`
`r text_shared_preamble_two`
`r text_shared_preamble_thr`
```{python}
import pprint
import copy as copy
```
#### Loop Through a Dictionary
Given a dictionary, loop through all of its elements
```{python}
dc_speckey_dict = {0: 'mpoly_1',
1: 'ng_s_t',
2: 'ng_s_d',
3: 'ng_p_t',
4: 'ng_p_d'}
for speckey_key, speckey_val in dc_speckey_dict.items():
print('speckey_key:' + str(speckey_key) + ', speckey_val:' + speckey_val)
```
#### Convert a List to a Dictionary
There is a list with different types of elements. Use the name of the list as the key, with value index added in as a part of the key, the value is the value of the dictionary.
```{python}
# List
ls_combo_type = ["e", "20201025x_esr_list_tKap_mlt_ce1a2", ["esti_param.kappa_ce9901", "esti_param.kappa_ce0209"], 1, "C1E31M3S3=1"]
# List name as string variable
st_ls_name = f'{ls_combo_type=}'.split('=')[0]
# Convert to dict
dc_from_list = {st_ls_name + '_i' + str(it_idx) + 'o' + str(len(ls_combo_type)) : ob_val
for it_idx, ob_val in enumerate(ls_combo_type)}
# Print
pprint.pprint(dc_from_list, width=1)
```
#### Select One Key-value Pair
Given a dictionary, select a single key-value pair, based on either the key or the value.
```{python}
# select by key
ls_it_keys = [0, 4]
dc_speckey_dict_select_by_key = {it_key: dc_speckey_dict[it_key] for it_key in ls_it_keys}
print(f'{dc_speckey_dict_select_by_key=}')
# select by value
ls_st_keys = ['ng_s_d', 'ng_p_d']
dc_speckey_dict_select_by_val = {it_key: st_val for it_key, st_val in dc_speckey_dict.items()
if st_val in ls_st_keys}
print(f'{dc_speckey_dict_select_by_val=}')
```
See [Get key by value in dictionary](https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary).
#### Copying Dictionary and Updating Copied Dictionary
First, below, it looks as if the default dictionary has been copied, and that the updates to the dictionary will only impact the *dc_invoke_main_args*, but that is not the case:
```{python}
# list update
dc_invoke_main_args_default = {'speckey': 'ng_s_t',
'ge': False,
'multiprocess': False,
'estimate': False,
'graph_panda_list_name': 'min_graphs',
'save_directory_main': 'simu',
'log_file': False,
'log_file_suffix': ''}
dc_invoke_main_args = dc_invoke_main_args_default
dc_invoke_main_args['speckey'] = 'b_ge_s_t_bis'
dc_invoke_main_args['ge'] = True
print(f'speckey in dc_invoke_main_args is {dc_invoke_main_args["speckey"]}.')
print(f'speckey in dc_invoke_main_args_default is {dc_invoke_main_args_default["speckey"]}.')
```
Now this has the intended result. After updating the deep-copied dictionary, the key-values in the original dictionary are preserved:
```{python}
# list update
dc_invoke_main_args_default = {'speckey': 'ng_s_t',
'ge': False,
'multiprocess': False,
'estimate': False,
'graph_panda_list_name': 'min_graphs',
'save_directory_main': 'simu',
'log_file': False,
'log_file_suffix': ''}
# deep copy and update
dc_invoke_main_args = copy.deepcopy(dc_invoke_main_args_default)
dc_invoke_main_args['speckey'] = 'b_ge_s_t_bis'
dc_invoke_main_args['ge'] = True
print(f'speckey in dc_invoke_main_args_default is {dc_invoke_main_args_default["speckey"]}.')
print(f'speckey in dc_invoke_main_args is {dc_invoke_main_args["speckey"]}.')
# deep copy and update again
dc_invoke_main_args = copy.deepcopy(dc_invoke_main_args_default)
dc_invoke_main_args['speckey'] = 'b_ge_s_t_bis_new'
dc_invoke_main_args['ge'] = False
print(f'speckey in dc_invoke_main_args is {dc_invoke_main_args["speckey"]}.')
```
- [copy and deepcopy](https://docs.python.org/2/library/copy.html)
- [Deep copy of a dict in python](https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python)
#### Create a List of Dictionaries
```{python}
import datetime
import pprint
ls_dc_exa = [
{"file": "mat_matlab",
"title": "One Variable Graphs and Tables",
"description": "Frequency table, bar chart and histogram",
"val": 1,
"date": datetime.date(2020, 5, 2)},
{"file": "mat_two",
"title": "Second file",
"description": "Second file.",
"val": [1, 2, 3],
"date": datetime.date(2020, 5, 2)},
{"file": "mat_algebra_rules",
"title": "Opening a Dataset",
"description": "Opening a Dataset.",
"val": 1.1,
"date": datetime.date(2018, 12, 1)}
]
pprint.pprint(ls_dc_exa, width=1)
```
#### Iteratively Add to A Dictionary
Iteratively add additional Key and Value pairs to a dictionary.
```{python}
ls_snm_tex = ["file1.tex", "file2.tex", "file3.tex"]
ls_snm_pdf = ["file1.pdf", "file2.pdf", "file3.pdf"]
dc_tex_pdf = {}
for tex, pdf in zip(ls_snm_tex, ls_snm_pdf):
dc_tex_pdf[tex] = pdf
pprint.pprint(dc_tex_pdf, width=1)
```
#### Select by Keys Dictionaries from list of Dictionaries
Given a list of dictionary, search if key name is in list:
```{python}
# string to search through
ls_str_file_ids = ['mat_matlab', 'mat_algebra_rules']
# select subset
ls_dc_selected = [dc_exa
for dc_exa in ls_dc_exa
if dc_exa['file'] in ls_str_file_ids]
# print
pprint.pprint(ls_dc_selected, width=1)
```
Search and Select by Multiple Keys in Dictionary. Using two keys below:
```{python}
# string to search through
ls_str_file_ids = ['mat_matlab', 'mat_algebra_rules']
# select subset
ls_dc_selected = [dc_exa
for dc_exa in ls_dc_exa
if ((dc_exa['file'] in ls_str_file_ids)
and
(dc_exa['val']== 1))]
# print
pprint.pprint(ls_dc_selected, width=1)
```
#### Drop Element of Dictionary
Drop element of a dictionary inside a list:
```{python}
# Dictionary
dc_test = [{"file": "mat_matlab_1",
"title": "One Variable Graphs and Tables",
"description": "Frequency table, bar chart and histogram",
"val": 1,
"date": datetime.date(2020, 5, 2)},
{"file": "mat_matlab_2",
"val": "mat_matlab_2"}]
# Drop
del dc_test[0]['val']
del dc_test[0]['file']
del dc_test[0]['description']
del dc_test[1]['val']
# Print
pprint.pprint(dc_test, width=1)
```
#### Select Element of List from Dictionary of List with Dictionary of Index
There are several key parameters of a model. There is a set of allowed, possible values for each parameter. Store these in a dictionary, using list to store all allowed values. When the function is called, a dictionary with the same keys, representing parameter names, will be the input to the function, the values of this dictionary are index corresponding to elements of the allowed list for each key.
Possibility one, where we select only the subset of values specified in the dictionary of index:
```{python}
# Dict of List of Allowed values
dc_ls_execute_type = {'model_assumption': ['', 'ITG', 'GE', 'ITG_GE'],
'compute_size': ['', 'x', 'd'],
'esti_size': ['tinytst', 'medtst', 'bigtst'],
'esti_param': ['esti_tst_tKap', 'esti_tst_tvars'],
'call_type': ['aws', 'vig', 'cmd'],
'param_date': ['20201025']}
# Dict of index selection from allowed values
dc_it_execute_type = {'model_assumption': 0, 'compute_size': 0, 'esti_size': 1, 'esti_param': 0}
# Select values from list
dc_selected_vals = {param_key:dc_ls_execute_type[param_key][val_idx]
for param_key, val_idx in dc_it_execute_type.items()}
pprint.pprint(dc_selected_vals, width=1)
```
If the input list does not specify one of the parameters, use the default value (update the dict):
```{python}
# Default index, assume first element is default
dc_execute_default = {param_key:val_list[0] for param_key, val_list in dc_ls_execute_type.items()}
# Overrid default with externally specified values
dc_execute_default.update(dc_selected_vals)
pprint.pprint(dc_execute_default, width=1)
```