It hasn't been long since I started learning python, but I really want to dig in it. And dig it hard. So here is a task I've been studying for a while but haven't cracked yet:
I am given a mixed combination of nested dictionaries and lists (let's call it "combination"), and I need to implement function that will allow accessing nested elements as object attributes, also somehow treating combination elements as iterable. This 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 that
list(function(combination).items.field1)
will give: ['a', 'c']
, and
list(function(combination).item1)
will give: [3.14]
.
Edit As mentioned by @FM, I missed description of handling non-dict 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 the function like return Struct(**combination)
While being very nifty, it is only the first step to the desired result.
But as the next step needs to go deeper, it overwhelms me and I can't make it on myself.
Therefore, I kindly ask for your help.
Michael.