1 Dictionary

Go to the RMD, PDF, or HTML version of this file. Go back to Python Code Examples Repository (bookdown site) or the pyfan Package (API).

import pprint
import copy as copy

1.1 Loop Through a Dictionary

Given a dictionary, loop through all of its elements

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)
## speckey_key:0, speckey_val:mpoly_1
## speckey_key:1, speckey_val:ng_s_t
## speckey_key:2, speckey_val:ng_s_d
## speckey_key:3, speckey_val:ng_p_t
## speckey_key:4, speckey_val:ng_p_d

1.2 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.

# 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)
## {'ls_combo_type_i0o5': 'e',
##  'ls_combo_type_i1o5': '20201025x_esr_list_tKap_mlt_ce1a2',
##  'ls_combo_type_i2o5': ['esti_param.kappa_ce9901',
##                         'esti_param.kappa_ce0209'],
##  'ls_combo_type_i3o5': 1,
##  'ls_combo_type_i4o5': 'C1E31M3S3=1'}

1.3 Select One Key-value Pair

Given a dictionary, select a single key-value pair, based on either the key or the value.

# 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
## dc_speckey_dict_select_by_key={0: 'mpoly_1', 4: 'ng_p_d'}
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=}')
## dc_speckey_dict_select_by_val={2: 'ng_s_d', 4: 'ng_p_d'}

See Get key by value in dictionary.

1.4 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:

# 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"]}.')
## speckey in dc_invoke_main_args is b_ge_s_t_bis.
print(f'speckey in dc_invoke_main_args_default is {dc_invoke_main_args_default["speckey"]}.')
## speckey in dc_invoke_main_args_default is b_ge_s_t_bis.

Now this has the intended result. After updating the deep-copied dictionary, the key-values in the original dictionary are preserved:

# 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"]}.')
## speckey in dc_invoke_main_args_default is ng_s_t.
print(f'speckey in dc_invoke_main_args is {dc_invoke_main_args["speckey"]}.')
# deep copy and update again
## speckey in dc_invoke_main_args is b_ge_s_t_bis.
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"]}.')
## speckey in dc_invoke_main_args is b_ge_s_t_bis_new.

1.5 Create a List of Dictionaries

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)
## [{'date': datetime.date(2020, 5, 2),
##   'description': 'Frequency '
##                  'table, '
##                  'bar '
##                  'chart '
##                  'and '
##                  'histogram',
##   'file': 'mat_matlab',
##   'title': 'One '
##            'Variable '
##            'Graphs '
##            'and '
##            'Tables',
##   'val': 1},
##  {'date': datetime.date(2020, 5, 2),
##   'description': 'Second '
##                  'file.',
##   'file': 'mat_two',
##   'title': 'Second '
##            'file',
##   'val': [1,
##           2,
##           3]},
##  {'date': datetime.date(2018, 12, 1),
##   'description': 'Opening '
##                  'a '
##                  'Dataset.',
##   'file': 'mat_algebra_rules',
##   'title': 'Opening '
##            'a '
##            'Dataset',
##   'val': 1.1}]

1.6 Iteratively Add to A Dictionary

Iteratively add additional Key and Value pairs to a dictionary.

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)
## {'file1.tex': 'file1.pdf',
##  'file2.tex': 'file2.pdf',
##  'file3.tex': 'file3.pdf'}

1.7 Select by Keys Dictionaries from list of Dictionaries

Given a list of dictionary, search if key name is in list:

# 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)
## [{'date': datetime.date(2020, 5, 2),
##   'description': 'Frequency '
##                  'table, '
##                  'bar '
##                  'chart '
##                  'and '
##                  'histogram',
##   'file': 'mat_matlab',
##   'title': 'One '
##            'Variable '
##            'Graphs '
##            'and '
##            'Tables',
##   'val': 1},
##  {'date': datetime.date(2018, 12, 1),
##   'description': 'Opening '
##                  'a '
##                  'Dataset.',
##   'file': 'mat_algebra_rules',
##   'title': 'Opening '
##            'a '
##            'Dataset',
##   'val': 1.1}]

Search and Select by Multiple Keys in Dictionary. Using two keys below:

# 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)
## [{'date': datetime.date(2020, 5, 2),
##   'description': 'Frequency '
##                  'table, '
##                  'bar '
##                  'chart '
##                  'and '
##                  'histogram',
##   'file': 'mat_matlab',
##   'title': 'One '
##            'Variable '
##            'Graphs '
##            'and '
##            'Tables',
##   'val': 1}]

1.8 Drop Element of Dictionary

Drop element of a dictionary inside a list:

# 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)
## [{'date': datetime.date(2020, 5, 2),
##   'title': 'One '
##            'Variable '
##            'Graphs '
##            'and '
##            'Tables'},
##  {'file': 'mat_matlab_2'}]

1.9 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:

# 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)
## {'compute_size': '',
##  'esti_param': 'esti_tst_tKap',
##  'esti_size': 'medtst',
##  'model_assumption': ''}

If the input list does not specify one of the parameters, use the default value (update the dict):

# 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)
## {'call_type': 'aws',
##  'compute_size': '',
##  'esti_param': 'esti_tst_tKap',
##  'esti_size': 'medtst',
##  'model_assumption': '',
##  'param_date': '20201025'}