Python3 字典使用"."来获取数据?

查看:105
本文介绍了Python3 字典使用"."来获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

def gets( t, s, d=None ):
    '''
        拓展字典的get方法
        gets( 字典, key [, '默认值'])
        dict = {'a':{'b':1}}
        gets( dict, 'a.b', 'xx')
        返回 值 | 默认值(未指定返回None)
    '''
    if not t: return d
    for k in s.split('.'):
        if type(t) == list and k.lstrip('-').isdigit():
            l = k = int(k)
            if k < 0: l = abs(k) - 1
            if len(t) > l: t = t[k]; continue
        elif type(t) == dict and k in t:
            t = t[k]; continue
        else:
            return d
    return t

这是我自己写的, 请问有需要改进的地方吗?

还有, 能否改为 dict.gets('a.b','xx') ?

解决方案

class mydict(dict):
    def dict2til(self, d):
        '''
            将字典平铺
        '''
        for k, v in d.items():
            if isinstance(v, (list, dict)):
                lst = v if isinstance(v, list) else [v]
                for item in lst:
                    item = {"{}.{}".format(k, a): b for a, b in item.items()}
                    #python3.3+, 可以这样写yield from self.dict2til(item)
                    for k1, v1 in self.dict2til(item):
                        yield k1, v1

            yield k, v

    def gets(self, k, d=None):
        dic = {k: v for k, v in self.dict2til(self)}
        return d if k not in dic.keys() else dic.get(k)


d = mydict({'a':{'b':1}})

print d.gets('a')
print d.gets('a.b')
print d.gets('a.b.c', '2')

这篇关于Python3 字典使用&quot;.&quot;来获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆