How can I iterate through a dictionary and use context managers in Python?

Viewed 37

The dictionary I am trying to iterate through has the following structure:

d = {
"main_key_1": {
    "name": "Name1",
    "context": "Context1",
    "message": "Message1",
    "date": "Date1",
    "reference": "Reference1"
    },
"main_key_2": {
    "name": "Name2",
    "context": "Context2",
    "message": "Message2",
    "date": "Date2",
    "reference": "Reference2"
    }
}

This is the way I tried to iterate:

for item in d.items():
    from_context = f"from {item[1]['context']}"

    with context('given a descriptor'):
        with context(from_context):
            with before.all:
                self.descriptor = item[1]['message']

            with context('that contains a date'):
                with it('recognizes the date'):
                    adapter = MessageToDatetAdapter(self.descriptor)

                    result = adapter.is_a_date()

                    expect(result).to(equal(True))

                with it('extracts the date data'):
                    adapter = MessageToDatetAdapter(self.descriptor)

                    result = adapter.adapt()
                    expect(result['date']).to(equal(item[1]['date']))
                    expect(result['reference']).to(item[1]['reference'])

The first iteration would be something like below:

    with context('given a descriptor'):
        with context('from Context1'):
            with before.all:
                self.descriptor = 'Message1'

            with context('that contains a date'):
                with it('recognizes the date'):
                    adapter = MessageToDatetAdapter(self.descriptor)

                    result = adapter.is_a_date()

                    expect(result).to(equal(True))

                with it('extracts the date data'):
                    adapter = MessageToDatetAdapter(self.descriptor)

                    result = adapter.adapt()
                    expect(result['date']).to('Date1')
                    expect(result['reference']).to('Reference1')

However, it seems like this is not correct. It looks like I cannot iterate through all the dictionary items.

0 Answers
Related