簡體   English   中英

如何刪除嵌套的鍵並創建一個新的字典並將兩者與一個 ID 鏈接起來?

[英]How can I remove nested keys and create a new dict and link both with an ID?

我有個問題。 我有一個字典my_Dict 這有點嵌套。 但是,我想“清理”字典my_Dict ,我的意思是我想分離所有嵌套的字典並生成一個唯一的 ID,以便以后可以再次找到相應的 object。 例如,我有detail: {...} ,這個嵌套的,稍后應該是 map 一個獨立的字典my_Detail_Dict ,此外, detail應該在my_Dict中收到一個唯一的 ID。 不幸的是,我給出的清單是空的。 我怎樣才能取出我被宰殺的鑰匙並給他們一個 ID?

my_Dict = {
'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }   
 }


def nested_dict(my_Dict):
    my_new_dict_list = []
    for key in my_Dict.keys():
        #print(f"Looking for {key}")
        if isinstance(my_Dict[key], dict):
            print(f"{key} is nested")


            # Add id to nested stuff
            my_Dict[key]["__id"] = 1        
            my_nested_Dict = my_Dict[key]
            # Delete all nested from the key
            del my_Dict[key]
            # Add id to key, but not the nested stuff
            my_Dict[key] = 1

            my_new_dict_list.append(my_Dict[key])
        my_new_dict_list.append(my_Dict)
        return my_new_dict_list

nested_dict(my_Dict)

[OUT] []
# What I want

[my_Dict, my_Details_Dict, my_Data_Dict]

我擁有的

{'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {'selector': {'number': '12312',
   'isTrue': True,
   'requirements': [{'type': 'customer', 'requirement': '1'}]}}}

我想要的是

my_Dict = {'_key': '1',
 'group': 'test',
 'data': 18,
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': 22}


my_Data_Dict = {'__id': 18}

my_Detail_Dict = {'selector': {'number': '12312',
   'isTrue': True,
   'requirements': [{'type': 'customer', 'requirement': '1'}]}, '__id': 22}

如果我理解正確的話,您希望自動使每個嵌套字典成為它自己的變量,並將其從主字典中刪除。

查找嵌套詞典並將它們從主詞典中刪除並不困難。 但是,出於各種原因,不建議將它們自動分配給變量。 相反,我要做的是將所有這些字典存儲在一個列表中,然后手動將它們分配給一個變量。

# Prepare a list to store data in
inidividual_dicts = []

id_index = 1
for key in my_Dict.keys():
    # For each key, we get the current value
    value = my_Dict[key]
    
    # Determine if the current value is a dictionary. If so, then it's a nested dict
    if isinstance(value, dict): 
        print(key + " is a nested dict")
        
        # Get the nested dictionary, and replace it with the ID
        dict_value = my_Dict[key]
        my_Dict[key] = id_index

        # Add the id to previously nested dictionary
        dict_value['__id'] = id_index
        
        
        id_index = id_index + 1 # increase for next nested dic
        
        inidividual_dicts.append(dict_value) # store it as a new dictionary
        

# Manually write out variables names, and assign the nested dictionaries to it. 
[my_Details_Dict, my_Data_Dict] = inidividual_dicts

以下代碼片段將解決您要執行的操作:

my_Dict = {
'_key': '1',
 'group': 'test',
 'data': {},
 'type': '',
 'code': '007',
 'conType': '1',
 'flag': None,
 'createdAt': '2021',
 'currency': 'EUR',
 'detail': {
        'selector': {
            'number': '12312',
            'isTrue': True,
            'requirements': [{
                'type': 'customer',
                'requirement': '1'}]
            }
        }   
 }

def nested_dict(my_Dict):
    # Initializing a dictionary that will store all the nested dictionaries
    my_new_dict = {}
    idx = 0
    for key in my_Dict.keys():
        # Checking which keys are nested i.e are dictionaries
        if isinstance(my_Dict[key], dict):
            # Generating ID
            idx += 1

            # Adding generated ID as another key
            my_Dict[key]["__id"] = idx

            # Adding nested key with the ID to the new dictionary
            my_new_dict[key] = my_Dict[key]

            # Replacing nested key value with the generated ID
            my_Dict[key] = idx
    
    # Returning new dictionary containing all nested dictionaries with ID
    return my_new_dict

result = nested_dict(my_Dict)
print(my_Dict)

# Iterating through dictionary to get all nested dictionaries
for item in result.items():
    print(item)

暫無
暫無

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

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