user2560609
user2560609

Reputation: 79

Python: Access nested datastructures

The value of my opening_hours key is a dictionary

and the value of periodsis a list which I would like to extract.

dic = {u'opening_hours': {u'open_now': True, u'periods': [{u'close': {u'day': 1, u'time': u'0100'}, u'open': {u'day': 0, u'time': u'0800'}}, {u'close': {u'day': 2, u'time': u'0100'}, u'open': {u'day': 1, u'time': u'0800'}}, {u'close': {u'day': 3, u'time': u'0100'}, u'open': {u'day': 2, u'time': u'0800'}}, {u'close': {u'day': 4, u'time': u'0100'}, u'open': {u'day': 3, u'time': u'0800'}}, {u'close': {u'day': 5, u'time': u'0100'}, u'open': {u'day': 4, u'time': u'0800'}}, {u'close': {u'day': 6, u'time': u'0100'}, u'open': {u'day': 5, u'time': u'0800'}}, {u'close': {u'day': 0, u'time': u'0100'}, u'open': {u'day': 6, u'time': u'0800'}}]}}

I'm stuck here, even though I was able to return the two keys(open_now and periods), I can't access periods' value.

How should I proceed?

>>> smalldict = dict[u'opening_hours']
>>> smallerdict = smalldict[u'periods']

Does this work?

Upvotes: 1

Views: 171

Answers (1)

Tadeck
Tadeck

Reputation: 137410

By using:

dic['opening_hours']['periods']

you retrieve a list. This is the value you are looking for. You can iterate through it, serialize etc. - this is all you need:

>>> periods = dic['opening_hours']['periods']
>>> for period in periods:
    print(period)


{u'close': {u'day': 1, u'time': u'0100'}, u'open': {u'day': 0, u'time': u'0800'}}
{u'close': {u'day': 2, u'time': u'0100'}, u'open': {u'day': 1, u'time': u'0800'}}
{u'close': {u'day': 3, u'time': u'0100'}, u'open': {u'day': 2, u'time': u'0800'}}
{u'close': {u'day': 4, u'time': u'0100'}, u'open': {u'day': 3, u'time': u'0800'}}
{u'close': {u'day': 5, u'time': u'0100'}, u'open': {u'day': 4, u'time': u'0800'}}
{u'close': {u'day': 6, u'time': u'0100'}, u'open': {u'day': 5, u'time': u'0800'}}
{u'close': {u'day': 0, u'time': u'0100'}, u'open': {u'day': 6, u'time': u'0800'}}

>>> for index, period in enumerate(periods, 1):
    print('Period number %s starts %s, day %s, and ends %s, day %s.' % (
        index,
        period['open']['time'],
        period['open']['day'],
        period['close']['time'],
        period['close']['day'],
    ))


Period number 1 starts 0800, day 0, and ends 0100, day 1.
Period number 2 starts 0800, day 1, and ends 0100, day 2.
Period number 3 starts 0800, day 2, and ends 0100, day 3.
Period number 4 starts 0800, day 3, and ends 0100, day 4.
Period number 5 starts 0800, day 4, and ends 0100, day 5.
Period number 6 starts 0800, day 5, and ends 0100, day 6.
Period number 7 starts 0800, day 6, and ends 0100, day 0.

Upvotes: 3

Related Questions