1

我的 opening_hours 键的值是一个字典

和 period 的值是我想提取的列表。

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

这行得通吗?

4

1 回答 1

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.
于 2013-07-09T16:03:12.437 回答