簡體   English   中英

如何遍歷所有嵌套字典以給出所有連接的父鍵及其值

[英]How to loop through all nested dictionary to give all the parent key concatenated and its value

dictionary={' items': { 'heading': 'Maps','description':'Maps123','imagepath':/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

我想要 output 的格式:

items/heading: Maps

items/description: Maps123

items/image_path: /music/images/v2/web_api-music.png

items/config/config1: abcd

items/config/config2: hello

db/username: xyz

db/password: xyz

version: v1

核實:

def flatten(x, parent=''):
    for key in list(x.keys()):
        if( type(x[key]) is dict ):
            flatten(x[key], parent+'/'+str(key))
        else:
            print(parent+'/'+str(key)+': ' + str(x[key]))

dictionary={'items': { 'heading': 'Maps','description':'Maps123','imagepath':'/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

flatten(dictionary)

script0 的答案導致 output 以正斜杠 ( / ) 開頭。 我稍微修改了script0的代碼:

def flatten(x, parent=''):
    for key in x.keys():
        if isinstance(x[key], dict) and parent == '': flatten(x[key], key)
        elif isinstance(x[key], dict) and parent != '': flatten(x[key], f"{parent}/{key}")
        elif not isinstance(x[key], dict) and parent == '': print(f"{key}: {x[key]}")
        else: print(f"{parent}/{key}: {x[key]}")

dictionary= {'items': { 'heading': 'Maps','description':'Maps123','imagepath':'/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

flatten(dictionary)

Output(沒有前導/):

items/heading: Maps
items/description: Maps123
items/imagepath: /music/images/
items/config/config1: 12
items/config/config2: 123
db/username: xyz
db/password: xyz
version: v1

請注意,您還可以創建一個新字典,將 output 的左側作為鍵,將右側作為值。

例如:

new_dict = {}

def flatten(x, parent=''):
    for key in x.keys():
        if isinstance(x[key], dict) and parent == '': flatten(x[key], key)
        elif isinstance(x[key], dict) and parent != '': flatten(x[key], f"{parent}/{key}")
        elif not isinstance(x[key], dict) and parent == '': new_dict[key] = x[key]
        else: new_dict[f"{parent}/{key}"] = x[key]

dictionary= {'items': { 'heading': 'Maps','description':'Maps123','imagepath':'/music/images/','config':{'config1':12,'config2':123}},'db':{'username':'xyz','password':'xyz'},'version':'v1'}

flatten(dictionary)
print(new_dict)

Output:

{'items/heading': 'Maps', 'items/description': 'Maps123', 'items/imagepath': '/music/images/', 'items/config/config1': 12, 'items/config/config2': 123, 'db/username': 'xyz', 'db/password': 'xyz', 'version': 'v1'}

遞歸 function 最適合這個。 它只需要檢查參數的類型並傳遞一個鍵的路徑:

def paths(D,P=[]):
    if isinstance(D,dict):
        return {p:v for k,d in D.items() for p,v in paths(d,P+[k]).items()} 
    else:
        return {"/".join(P):D}

Output:

print(paths(dictionary))

{'items/heading': 'Maps',
 'items/description': 'Maps123',
 'items/imagepath': '/music/images/',
 'items/config/config1': 12,
 'items/config/config2': 123,
 'db/username': 'xyz',
 'db/password': 'xyz',
 'version': 'v1'}

為了提高效率,您可以將 function 設為生成器,最后僅從提取的元組中創建字典。

def paths(D,P=[]):
    if isinstance(D,dict):
        yield from ((p,v) for k,d in D.items() for p,v in paths(d,P+[k])) 
    else:
        yield ("/".join(P),D)
                        
dictionary = dict(paths(dictionary))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM