Not so long ago, I began to study python, but I really want to dig it out. And dig it out. So, here is a task that I have been studying for a while, but have not yet cracked:
I am given a mixed combination of nested dictionaries and lists (let's call it " combination "), and I need to implement a function that will allow access to nested elements as attributes of the object, and also somehow handle the combination how iterable. It should look something like this:
combination = { 'item1': 3.14, 'item2': 42, 'items': [ 'text text text', { 'field1': 'a', 'field2': 'b', }, { 'field1': 'c', 'field2': 'd', }, ] } def function(combination): ...
so list(function(combination).items.field1) will give: ['a', 'c'] and
list(function(combination).item1) will give: [3.14] .
Edit As mentioned in @FM, I skipped the description of processing non-dictical elements: list(function(combination).items[0]) →> ['text text text']
I tried implementing a class (kudos to Marc ) to help me:
class Struct: def __init__(self, **entries): self.__dict__.update(entries)
and then using it in functions like return Struct(**combination)
Being very elegant, this is only the first step to the desired result.
But, since the next step should go deeper, it suppresses me, and I can not do it myself.
Therefore, I ask you for help.
Michael.
Michael spring
source share