简体   繁体   English

如何在嵌套字典中附加值

[英]How to append values in nested dictionary

dictnry={token1:{1:freq1,2:freq1a},
        ,token2:{1:freq2,2:freq2a,3:freq2b}
        ,token3:{3:freq4}}

How do i loop through a dictionary with int:dict as key:value pairs and append a new dictionary ( eg: {5:freq5} in token1 and {1:freq11} in token3 ) into its secondary existing dictionary我如何循环使用 int:dict 作为键:值对的字典并将新字典(例如{5:freq5}token1 {1:freq11}token3到其辅助现有字典中

for loop in dictnry:
   condition==true:
      for loop in sec_dictnry:
         p={5:freq5}  #p IS THE NEW DICTIONARY & 5 and freq5 will be substituted with variables
         dictnry[token1].append_for_dictionary_function_or_something(p) #WHAT DO I DO IN THIS LINE

dictnry={token1:{1:freq1,2:freq1a,5:freq5},
        ,token2:{1:freq2,2:freq2a,3:freq2b}
        ,token3:{3:freq4,1:freq11}}

You can create another dictionary of the things you want to add:您可以为要添加的内容创建另一个字典:

import json

d = {
    "token1": {
        1: "freq1",
        2: "freq1a",
    },
    "token2": {
        1: "freq2",
        2: "freq2a",
        3: "freq2b",
    },
    "token3": {
        3: "freq4",
    }
}

print("Before:")
print(json.dumps(d, indent=4))

key_entry_to_add = {
    "token1": {
        5: "freq5",
    },
    "token3": {
        1: "freq11",
    }
}

for key, entry in key_entry_to_add.items():
    entry_key, entry_val = next(iter(entry.items()))
    d[key][entry_key] = entry_val

print("After:")
print(json.dumps(d, indent=4, sort_keys=True))

Output:输出:

Before:
{
    "token1": {
        "1": "freq1",
        "2": "freq1a"
    },
    "token2": {
        "1": "freq2",
        "2": "freq2a",
        "3": "freq2b"
    },
    "token3": {
        "3": "freq4"
    }
}
After:
{
    "token1": {
        "1": "freq1",
        "2": "freq1a",
        "5": "freq5"
    },
    "token2": {
        "1": "freq2",
        "2": "freq2a",
        "3": "freq2b"
    },
    "token3": {
        "1": "freq11",
        "3": "freq4"
    }
}

You can simply loop over you dictionary and once the key is equal to the key you want to append some dict in its value and do it like the following你可以简单地遍历你的字典,一旦键等于你想要在它的值中附加一些字典的键,然后像下面那样做

Example例子

from pprint import pprint
dictionary = {
                'token1':{1:'freq1',2:'freq1a'},
                'token2':{1:'freq2',2:'freq2a',3:'freq2b'},
                'token3':{3:'freq4'}
            }
for x, y in dictionary.items():
    if x == 'token1':
        y[5] = 'freq5'
    if x == 'token3':
        y[1] = 'freq11'

pprint(dictionary)

Or或者

dictionary['token1'][5] = 'freq5'
dictionary['token3'][1] = 'freq11'

output输出

{'token1': {1: 'freq1', 2: 'freq1a', 5: 'freq5'},
 'token2': {1: 'freq2', 2: 'freq2a', 3: 'freq2b'},
 'token3': {1: 'freq11', 3: 'freq4'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM