Python 我如何正确使用字典;。更新;具有嵌套字典的嵌套循环中的函数

Python 我如何正确使用字典;。更新;具有嵌套字典的嵌套循环中的函数,python,json,loops,dictionary,nested,Python,Json,Loops,Dictionary,Nested,因此,我从web服务中提取字典格式的JSON,以获取有关特定产品的各种度量。我有一个嵌套循环,它拉入嵌套字典,我想将这些嵌套字典分配给唯一的产品(即键)。为了简单起见,我提供了一些示例代码,其中显示了我遇到的问题(尽管荒谬,但香蕉很神奇) 这将提供以下输出: { 'apple': {'fresh': {'US': 'GA'}}, 'banana': {'bad': {'Peru': 'Lima'}}, 'watermelon': {'fresh': {'Peru': 'Lim

因此,我从web服务中提取字典格式的JSON,以获取有关特定产品的各种度量。我有一个嵌套循环,它拉入嵌套字典,我想将这些嵌套字典分配给唯一的产品(即键)。为了简单起见,我提供了一些示例代码,其中显示了我遇到的问题(尽管荒谬,但香蕉很神奇)

这将提供以下输出:

{   'apple': {'fresh': {'US': 'GA'}},
    'banana': {'bad': {'Peru': 'Lima'}},
    'watermelon': {'fresh': {'Peru': 'Lima'}}}

我的问题:我想得到一本包含每个描述符的字典
[这个颜色,这个形状,这个味道]
作为一个键,但我只得到最后一项
这个味道
。我敢打赌这是因为我不正确地使用了
.update
,但我不确定实现这一点的“正确”方法。任何建议都很好

看看你的代码是做什么的。您的更新行与
test[i]={x:random.choice(farm)}
相同。因此,“test”键是水果(
i
),内部dict的键是
description
的一个成员。我不清楚你想要什么。您应该向我们展示您的完美输出是什么样子。
update()
不会递归合并,因此它会将元素替换为键
i
。似乎它可以回答您的问题。如果该解决方案位于另一个问题中,则应将其标记为重复。标记。谢谢看起来这是一个比我最初认为的更复杂的问题,看看那些关于另一个问题的评论吧!非常感谢。
import random
import collections.abc

#https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

test = {}
fruit = ['apple','banana','watermelon']

color = ['red','blue','green']
shape = ['oval','round','long']
taste = ['good','bad','fresh']
farm = [{'US': 'GA'}, {"Peru": "Lima"},{'US': 'New York'}] # this data in my use is actually more varied

for i in fruit:
    this_color = random.choice(color) # these represent making URLs to pull from
    this_shape = random.choice(shape)
    this_taste = random.choice(taste)
    description = [this_color,this_shape,this_taste]
    for x in description:
        # this line would be pulling requests of dictionary formatted JSONs from the URLS
        update(test, {i: {x: random.choice(farm)}})
import random
import collections.abc

#https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
def update(d, u):
    for k, v in u.items():
        if isinstance(v, collections.abc.Mapping):
            d[k] = update(d.get(k, {}), v)
        else:
            d[k] = v
    return d

test = {}
fruit = ['apple','banana','watermelon']

color = ['red','blue','green']
shape = ['oval','round','long']
taste = ['good','bad','fresh']
farm = [{'US': 'GA'}, {"Peru": "Lima"},{'US': 'New York'}] # this data in my use is actually more varied

for i in fruit:
    this_color = random.choice(color) # these represent making URLs to pull from
    this_shape = random.choice(shape)
    this_taste = random.choice(taste)
    description = [this_color,this_shape,this_taste]
    for x in description:
        # this line would be pulling requests of dictionary formatted JSONs from the URLS
        update(test, {i: {x: random.choice(farm)}})