Python:访问嵌套数据结构

时间:2013-07-09 15:58:57

标签: python data-structures

我的opening_hours键的值是字典

和句号的值是我想要提取的列表。

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'}}]}}

我被困在这里,即使我能够返回两个键(open_now和句点), 我无法访问期间的价值。

我该怎么办?

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

这有用吗?

1 个答案:

答案 0 :(得分:3)

使用:

dic['opening_hours']['periods']

检索列表。这是您正在寻找的价值。您可以遍历它,序列化等等 - 这就是您所需要的:

>>> 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.