更好的方法迭代到python中的字典,以避免许多嵌套的for循环

时间:2012-08-25 05:59:12

标签: python python-2.6

有没有更好的方法来迭代我的字典数据而不使用3嵌套for loops,就像我现在正在做的那样,给出下面这些数据?顺便说一下,我正在使用python 2.6。

data = {'08132012': 
           {
            'id01': [{'code': '02343','status': 'P'},{'code': '03343','status': 'F'}],
            'id02': [{'code': '18141','status': 'F'},{'code': '07777','status': 'F'}]
           }
        }   

以下是3个for循环当前代码:

  for date in data:
      for id in data[date]:
          for trans in data[date][id]:
              print "Date: %s" % date
              print "Processing id: %s" % id
              print trans['code']
              print trans['status']

              //query to database

已编辑:有效数据值

3 个答案:

答案 0 :(得分:8)

鉴于数据的嵌套特性,我认为没有办法避免某些嵌套循环。

但是,您可以通过为数据编写flattening生成器来避免嵌套大部分程序逻辑,如下所示:

def flatten(data):
    for date in data:
        for id in data[date]:
            for trans in data[date][id]:
                yield (date, id, trans)

def process(data):
    for date, id, trans in flatten(data):
        # do stuff with date, id, trans

答案 1 :(得分:4)

如果不了解数据来源的更多细节,我想要的解决方案是,如果可以更改data的存储结构,可以考虑使用namedtuple。它会使事情变得更清晰,更具可读性。

以下是一个例子:

>>> from collections import namedtuple
>>> Record = namedtuple('Record', ['date', 'id', 'code', 'status'])
>>> records = []
>>> records.append(Record('08132012', 'id01', '02343','P'))
>>> records.append(Record('08132012', 'id01', '03343','F'))
>>> records.append(Record('08132012', 'id02', '18131','F'))
>>> records.append(Record('08132012', 'id02', '07777','F'))
>>> for record in records:
...     print "Date: %s" %record.date
...     print "Processing id: %s" %record.id
...     print record.code
...     print record.status
... 
Date: 08132012
Processing id: id01
02343
P
Date: 08132012
Processing id: id01
03343
F
Date: 08132012
Processing id: id02
18131
F
Date: 08132012
Processing id: id02
07777
F

更有趣:

获取status为'F'的记录列表:

>>> Fs = [record for record in records if record.status == 'F']
>>> Fs
[Record(date='08132012', id='id01', code='03343', status='F'),
Record(date='08132012', id='id02', code='18131', status='F'),
Record(date='08132012', id='id02', code='07777', status='F')]

code排序:

>>> records.append(Record('08122012', 'id03', '00001', 'P'))
>>> records.sort(key=lambda x:x.code)
>>> records
[Record(date='08122012', id='id03', code='00001', status='P'),
 Record(date='08132012', id='id01', code='02343', status='P'),
 Record(date='08132012', id='id01', code='03343', status='F'),
 Record(date='08132012', id='id02', code='07777', status='F'),
 Record(date='08132012', id='id02', code='18131', status='F')]

答案 2 :(得分:3)

发电机非常简单:

>>> flat = ((d, id, t) for d in data for id in data[d] for t in data[d][id])
>>> for date, id, trans in flat:
...     print date, id, trans
...
08132012 id02 {'status': 'F', 'code': '18141'}
08132012 id02 {'status': 'F', 'code': '07777'}
08132012 id01 {'status': 'P', 'code': '02343'}
08132012 id01 {'status': 'F', 'code': '03343'}
>>>