Skip to content

Instantly share code, notes, and snippets.

@geoffreygarrett
Created June 21, 2019 21:27
Show Gist options
  • Save geoffreygarrett/eae35815d9b1b4a1d43cff8f1d9b0c9c to your computer and use it in GitHub Desktop.
Save geoffreygarrett/eae35815d9b1b4a1d43cff8f1d9b0c9c to your computer and use it in GitHub Desktop.
Enumerate list of dictionaries based on key value.
class ClassContainer:
def __init__(self):
# The guessed data structure of the OP's class, as code was not provided. (Needed for reproduction)
self.meta = {"A": []}
# This would be required in the class for proposed solution.
# It is however not needed if set_data is only used once in an instantiated classes lifetime.
self.type_counter = dict() # or {}
def set_data(self, data):
"""
OP's original set_data method.
:param data:
example = [
{"type": "calculation", "result": "valA"},
{"type": "measurement", "result": "valB"},
{"type": "measurement", "result": "valC"}]
:return: None
"""
typecalc = list(item for item in data if item["type"] == "calculation")
typemeas = list(item for item in data if item["type"] == "measurement")
if isinstance(typecalc, list):
for count, filtered1 in enumerate(typecalc):
calc = ('calculation/' + str(count + 1) + '/')
filter1 = {'id': calc}
filter1.update(filtered1)
self.meta['A'].append(filter1)
if isinstance(typemeas, list):
for count, filtered2 in enumerate(typemeas):
calc = ('measurement/' + str(count + 1) + '/')
filter2 = {'id': calc}
filter2.update(filtered2)
self.meta['A'].append(filter2)
def set_data_generalised(self, data):
"""
OP's desired generalised set_data method.
:param data:
example = [
{"type": "calculation", "result": "valA"},
{"type": "measurement", "result": "valB"},
{"type": "measurement", "result": "valC"}]
:return: None
"""
for entry in data:
if entry["type"] in self.type_counter.keys():
self.type_counter[entry["type"]] += 1
else:
self.type_counter[entry["type"]] = 1
calc = (entry["type"] + "/" + str(self.type_counter[entry["type"]]) + '/')
# (Suggestion) If using Python3, I suggest using:
# calc = f"{entry['type']}/{self.type_counter[entry['type']]}/"
self.meta["A"].append(
{"id": calc,
"result": entry["result"],
"type": entry["type"]})
if __name__ == "__main__":
import json
# Simple pretty print while developing solution.
def pretty_print_dictionary(dictionary):
print(json.dumps(dictionary, indent=4, sort_keys=True))
data = [
{"type": "calculation", "result": "valA"},
{"type": "measurement", "result": "valB"},
{"type": "measurement", "result": "valC"}]
# OP's original set_data method.
test1 = ClassContainer()
test1.set_data(data)
before = test1.meta
pretty_print_dictionary(before)
# Test new set_data method.
test2 = ClassContainer()
test2.set_data_generalised(data)
generalised = test2.meta
pretty_print_dictionary(generalised)
# Assert both return the same results.
assert (before == generalised)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment