zoukankan      html  css  js  c++  java
  • python 通用字典方法

    版本1

    方法

    # 不传返回所有属性,传入props只返回传入的对应属性
    def m_dict(obj, props=[]):
        result = {}
        target = obj if len(props)==0 else props
        for i in target:
            try:
                result[i] = getattr(obj, i) if hasattr(obj, i) else obj[i]
            except:
                pass
        return result

    用法

    print m_dict(对象, props=[属性1, 属性2])

    可传入orm对象,sql查询结果,字典

    如传入props,则返回传入的元素构成字典

    不传props,则返回所有元素构成的字典

    版本2

    方法

    # 不传返回所有属性,传入props只返回传入的对应属性
    def m_dict(obj, props=[]):
        result = {}
        temp = obj.__dict__ if hasattr(obj, '__dict__') else obj
        target = temp if len(props)==0 else props
        for i in target:
            if not i.startswith('_'):
                try:
                    result[i] = getattr(obj, i) if hasattr(obj, i) else obj[i]
                except:
                    pass
        return result

     

    版本2测试

    orm

            session = DBSession()
            spiders = session.query(SpiderRule).filter(SpiderRule.state==2)
            for spider in spiders:
                print m_dict(spider,props=['id', 'name'])
                print m_dict(spider)

    dict

        a = {
            'a':1,
            'b':2,
            'c':3
        }
        print m_dict(a,'a')
        print m_dict(a)

  • 相关阅读:
    Git 总结
    .net报错大全
    对于堆和栈的理解
    html 局部打印
    c#面试问题总结
    算法题总结
    h5-plus.webview
    堆和栈,引用类型,值类型,指令,指针
    .NET framework具体解释
    前端之间的url 传值
  • 原文地址:https://www.cnblogs.com/lurenjia1994/p/9585375.html
Copyright © 2011-2022 走看看