10
{'action_name':'mobile signup',
    'functions':[{'name':'test_signUp',
                  'parameters':{'username':'max@getappcard.com',
                                'password':'12345',
                                'mobileLater':'123454231',
                                'mobile':'1e2w1e2w',
                                'card':'1232313',
                                'cardLater':'1234321234321'}}],
    'validations':[
            {'MOB_header':'My stores'},
            {'url':"/stores/my"}]}

我想将此字典的所有键和值作为列表获取(在它们是字典或数组的值之外)

打印结果应该是这样的:

action name = mobile signup
name = test_signUp
username : max@getappcard.com
password : 12345
mobileLater: 123454231
mobile : 1e2w1e2w
card : 1232313 
cardLater : 1234321234321
MOB_header : My stores
4

3 回答 3

9

您可能希望使用递归函数来提取所有key, value对。

def extract(dict_in, dict_out):
    for key, value in dict_in.iteritems():
        if isinstance(value, dict): # If value itself is dictionary
            extract(value, dict_out)
        elif isinstance(value, unicode):
            # Write to dict_out
            dict_out[key] = value
    return dict_out

这种东西。我来自 C++ 背景,所以我不得不用谷歌搜索所有语法。

于 2012-05-13T06:08:26.867 回答
0

有点晚了,但对于 python 3.8,你可以使用yield from

def dictitems2list(d):
    for k, v in d.items():
        yield k
        if isinstance(v, dict):
            yield from get_all_items(v)
        else:
            yield v

all_itemt = list(dict2items(d))
于 2021-05-03T12:27:43.247 回答
0

我已经从这个链接进行了一些修改,以获取字典列表和字典的嵌套字典中的所有键和值:

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        elif type(value) is list:
            yield (key, value)
            for i in value:
                if type(i) is dict:
                    yield from recursive_items(i)
        else:
            yield (key, value)

for i in recursive_items(your_dict):
    print(i) #print out tuple of (key, value)

输出:

('action_name', 'mobile signup')
('functions', [{'name': 'test_signUp', 'parameters': {'username': 
'max@getappcard.com', 'password': '12345', 'mobileLater': '123454231', 'mobile': 
'1e2w1e2w', 'card': '1232313', 'cardLater': '1234321234321'}}])
('name', 'test_signUp')
('parameters', {'username': 'max@getappcard.com', 'password': '12345', 
'mobileLater': '123454231', 'mobile': '1e2w1e2w', 'card': '1232313', 
'cardLater': '1234321234321'})
('username', 'max@getappcard.com')
('password', '12345')
('mobileLater', '123454231')
('mobile', '1e2w1e2w')
('card', '1232313')
('cardLater', '1234321234321')
('validations', [{'MOB_header': 'My stores'}, {'url': '/stores/my'}])
('MOB_header', 'My stores')
('url', '/stores/my')
于 2022-01-03T16:20:17.283 回答