From e44f3c8fcac869047453ef94bbb5182540ea2a70 Mon Sep 17 00:00:00 2001 From: Daniel Weschke Date: Mon, 11 Feb 2019 11:42:47 +0100 Subject: [PATCH] add def for getting values out of the material data --- src/materials.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/src/materials.py b/src/materials.py index 992350b..51389a9 100755 --- a/src/materials.py +++ b/src/materials.py @@ -103,6 +103,9 @@ def search_keys(data, keys): from json import loads def find_values(key, json_repr): + """\ + Find values inside json string + """ results = [] def _decode_dict(a_dict): try: @@ -146,6 +149,19 @@ def print_quantity(quantity, prespaces=0): print(prespaces*' ' + '%s' % quantity) +def get_value(data, element): + """\ + Get value of nested dictionary. + If element is itself a list of length one, the element of the list is returned + """ + keys = element.split('/') + for key in keys: + data = data.get(key) + if data and len(data) == 1: + data = next(iter(data.values())) + return data + + def main(): """\ Main function @@ -209,25 +225,20 @@ def main(): if args.debug: print("data:") print_material(data) + mat_index = { + "rho": "Mechanical Properties/rho", + "E": "Mechanical Properties/E", + "R_p": "Mechanical Properties/Yield strength", + "R_m": "Mechanical Properties/R_m" + } for element in args.const_collection: # iter the way it is been entered as args - if element == "rho": - print_quantity(data['Mechanical Properties']['rho']) - elif element == "E": - print_quantity(data['Mechanical Properties']['E']) - elif element == "R_p": - if len(data['Mechanical Properties']['Yield strength']) == 1: - print_quantity(next(iter(data['Mechanical Properties']['Yield strength'].values()))) - else: - print_quantity(data['Mechanical Properties']['Yield strength']) - elif element == "R_m": - print_quantity(data['Mechanical Properties']['R_m']) + print_quantity(get_value(data, mat_index[element])) elif args.search: search_list = [element for element in args.search.split(',')] - if args.debug: - print("search_list: " + str(search_list)) data = read_material(args.materialname) if args.debug: + print("search_list: " + str(search_list)) print("data: " + data) data_dict = search_keys(data, keys=search_list) print_dict(data_dict)