search

Home  >  Q&A  >  body text

python gets all values ​​of dict

like:

p={
    'a':'aa',
    'b':{
    'b':'bb'
    }
}
print(dict(p).values())

Returns:

dict_values(['aa', {'b': 'bb'}])

What I want is aa and bb. How should I write it, thank you

滿天的星座滿天的星座2756 days ago641

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-05-18 10:56:30

    def values(d):
        for v in d.values():
            if isinstance(v, dict):
                for _ in values(v): yield _
            else:
                yield v
    
    data = values({1:1,2:{2:2,3:{3:3,4:4}}})
    
    for v in data:
        print(v)
    
    # 1 2 3 4

    If using python 3.3+, replace for _ in values(v): yield _ 可用 yield from values(v) with

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-18 10:56:30

    It seems that it can only be traversed

    # coding: utf-8
    
    p={
        'a':'aa',
        'b':{
            'b':'bb',
            'c': {
                'c': 'cc',
                'd': {
                    'd': 'dd'
                }
            }
        }
    }
    
    def f(d):
        nl = []
        for _ in d.values():
            nl += f(_) if isinstance(_, dict) else [_]
        return nl
    
    print f(p)

    reply
    0
  • Cancelreply