如何在嵌套字典中附加值

时间:2020-11-10 13:42:52

标签: python dictionary append

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

我如何遍历一个以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}}

2 个答案:

答案 0 :(得分:1)

您可以为要添加的内容创建另一个字典:

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))

输出:

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"
    }
}

答案 1 :(得分:0)

您只需在字典上循环即可,一旦键等于键,您想在其值后附加一些字典,然后像下面这样

示例

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)

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

输出

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