0

データを保存したい[年][月]=日

年と月の両方が口述の鍵となる可能性がある場合。

data [year] [month] .append(day)のような操作が可能である可能性があります。

4

2 に答える 2

2

ネストされた辞書を使用できます。

data[year] = {}
data[year][month] = [day]

これを少し簡単にするために、次を使用できますcollections.defaultdict

from collections import defaultdict

data = defaultdict(dict)

data[year][month] = [day]

あるいは:

def monthdict():
    return defaultdict(list)
data = defaultdict(monthdict)

data[year][month].append(day)

後者の構造のデモ:

>>> from collections import defaultdict
>>> def monthdict():
...     return defaultdict(list)
... 
>>> data = defaultdict(monthdict)
>>> data[2013][3].append(23)
>>> data
defaultdict(<function monthdict at 0x10c9d0500>, {2013: defaultdict(<type 'list'>, {3: [23]})})
于 2013-03-23T17:03:08.973 に答える
1

dict-of-dicts-of-lists を使用できますか?

data = {'1972' :  {
                   '01': ['a', 'list', 'of', 'things'],
                   '02': ['another', 'list', 'of', 'things'],
                  },
        '1973' :  {
                   '01': ['yet', 'another', 'list', 'of', 'things'],
                  },
        }        

>>> data['1972']['02']
['another', 'list', 'of', 'things']

>>> data['1972']['01'].append(42)
>>> data
{'1972': {'01': ['a', 'list', 'of', 'things', 42],
  '02': ['another', 'list', 'of', 'things']},
 '1973': {'01': ['yet', 'another', 'list', 'of', 'things']}}
于 2013-03-23T17:02:25.970 に答える