我有一个python OrderedDict列表:
Python 2.7.6 (default, Jun 16 2014, 11:06:18)
[GCC 4.2.1 Compatible FreeBSD Clang 3.3 (tags/RELEASE_33/final 183502)] on freebsd10
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> my_list = [OrderedDict([(u'SR_CODE', u''), (u'SR_ACCOUNT', u'JEF001'), (u'SR_NAME', u''), (u'SR_DISCGRP', u''), (u'SR_PRCLIST', u'STD'), (u'SR_OVDISC', 0.0), (u'SR_SET1DAY', 0), (u'SR_SET1PCT', 0.0), (u'SR_SET2DAY', None), (u'SR_SET2PCT', None), (u'SR_DEBTLTR', True), (u'SR_DEBTMIN', 1), (u'SR_TERMTYP', 1), (u'SR_TERMDAY', 0), (u'SR_SDSCDEL', None), (u'SR_VATINCL', None), (u'SR_LASTUPD', None)]), OrderedDict([(u'SR_CODE', u''), (u'SR_ACCOUNT', u'JEN001'), (u'SR_NAME', u''), (u'SR_DISCGRP', u''), (u'SR_PRCLIST', u'STD'), (u'SR_OVDISC', 0.0), (u'SR_SET1DAY', 0), (u'SR_SET1PCT', 0.0), (u'SR_SET2DAY', None), (u'SR_SET2PCT', None), (u'SR_DEBTLTR', True), (u'SR_DEBTMIN', 1), (u'SR_TERMTYP', 1), (u'SR_TERMDAY', 0), (u'SR_SDSCDEL', None), (u'SR_VATINCL', None), (u'SR_LASTUPD', None)]), OrderedDict([(u'SR_CODE', u''), (u'SR_ACCOUNT', u'MSJ001'), (u'SR_NAME', u''), (u'SR_DISCGRP', u''), (u'SR_PRCLIST', u'STD'), (u'SR_OVDISC', 0.0), (u'SR_SET1DAY', 0), (u'SR_SET1PCT', 0.0), (u'SR_SET2DAY', None), (u'SR_SET2PCT', None), (u'SR_DEBTLTR', True), (u'SR_DEBTMIN', 1), (u'SR_TERMTYP', 1), (u'SR_TERMDAY', 0), (u'SR_SDSCDEL', None), (u'SR_VATINCL', None), (u'SR_LASTUPD', None)]), OrderedDict([(u'SR_CODE', u''), (u'SR_ACCOUNT', u'IDE001'), (u'SR_NAME', u''), (u'SR_DISCGRP', u''), (u'SR_PRCLIST', u'STD'), (u'SR_OVDISC', 0.0), (u'SR_SET1DAY', 0), (u'SR_SET1PCT', 0.0), (u'SR_SET2DAY', None), (u'SR_SET2PCT', None), (u'SR_DEBTLTR', True), (u'SR_DEBTMIN', 1), (u'SR_TERMTYP', 1), (u'SR_TERMDAY', 0), (u'SR_SDSCDEL', None), (u'SR_VATINCL', None), (u'SR_LASTUPD', None)])]
获取列表索引值的正确方法是什么?' SR_ACCOUNT',' JEF001'
我可以检查account_id是否存在:
>>> if any(d.get('SR_ACCOUNT', None) == 'JEF001' for d in my_list):
但我不确定如何返回这个特定字典?
任何建议都非常感谢
答案 0 :(得分:0)
我应该使用生成器表达式http://www.python.org/dev/peps/pep-0289/
>>> next((item for item in my_list if item["SR_ACCOUNT"] == "JEF001"), None)
OrderedDict([(u'SR_CODE', u''), (u'SR_ACCOUNT', u'JEF001'), (u'SR_NAME', u''), (u'SR_DISCGRP', u''), (u'SR_PRCLIST', u'STD'), (u'SR_OVDISC', 0.0), (u'SR_SET1DAY', 0), (u'SR_SET1PCT', 0.0), (u'SR_SET2DAY', None), (u'SR_SET2PCT', None), (u'SR_DEBTLTR', True), (u'SR_DEBTMIN', 1), (u'SR_TERMTYP', 1), (u'SR_TERMDAY', 0), (u'SR_SDSCDEL', None), (u'SR_VATINCL', None), (u'SR_LASTUPD', None)])