python gets all values ​​of dict
滿天的星座
滿天的星座 2017-05-18 10:54:30
0
2
633

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

滿天的星座
滿天的星座

reply all(2)
巴扎黑
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

phpcn_u1582

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template