将for循环的结果添加到嵌套字典中的相同键中

时间:2018-09-25 17:28:54

标签: python-3.x dictionary nested tuples key

我有一本字典,其中包括一些子字典。每个子词典都有许多键。在也使用if条件运行for循环之后,将生成结果。我想将所有结果添加到所需的键下;但是我的代码实际上所做的就是添加循环的最后一次迭代的结果,从而替换上一次迭代的值。

但是,实际上,我想打印所有结果。

for item in list1:          #item is a tuple & list1 has tuples in it
   if item == node_pair:        #node pair is another tuple
        high_p[i]["links"] = link_name           #"links" is the key 

所需的输出:    "links": [link_name1, link_name2, link_name3]
我得到什么:

"links" : link_name3

请指导我。

1 个答案:

答案 0 :(得分:0)

因此,每个子词典都需要具有列表作为值。您可以提前用列表预先填充每个子词典,但是使用seller_name = 'Lucas' url = 'http://sanyo.mapi/s3/e42390aac371?item_title=Branded%20boys%20Clothing&seller_name=102392852&buyer_item=106822419_1056424990' a = url.index('seller_name=') b = url.index('&', a) out = url.replace(url[a+12:b],seller_name) print(out) 按需创建它们会更容易。

setdefault