【问题标题】:How do I correctly use the dictionary ".update" function in nested loops with nested dictionaries [duplicate]如何在带有嵌套字典的嵌套循环中正确使用字典“.update”函数[重复]
【发布时间】:2021-08-10 01:46:57
【问题描述】:

因此,我从 Web 服务中提取字典格式的 JSON,以获取有关特定产品的各种指标。我有嵌套循环,可以拉出嵌套字典,我想将这些嵌套字典分配给唯一的产品(它们是键)。为了简单起见,我有一些示例代码显示了我遇到的问题(虽然荒谬,但香蕉很棒)。

import random
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
        test.update({i:{x: random.choice(farm)}})

这给出以下输出:

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

我的问题:我正在寻找一个字典,其中包含每个描述符 [this_color, this_shape, this_taste] 作为键,但我只将最后一项 this_taste 作为键。我敢打赌这是因为我错误地使用了.update,但我不确定实现这一点的“正确”方式。任何建议都会很棒!

【问题讨论】:

  • 看看你的代码做了什么。您的更新行与test[i] = {x: random.choice(farm)} 相同。因此,“测试”键是水果(i),而内部字典的键是description 的成员之一。我不清楚你想要什么。你应该向我们展示你的完美输出是什么样的。
  • update() 不会递归合并,所以它用键 i 替换元素。
  • This 似乎会回答你的问题。

标签: python json loops dictionary nested


【解决方案1】:
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)}})

【讨论】:

  • 如果该解决方案在另一个问题中,您应该将其标记为重复。
  • 已标记。谢谢!
  • 看起来这是一个比我最初认为的更复杂的问题,看看其他问题上的所有 cmet!谢谢!
猜你喜欢
  • 2017-07-22
  • 2022-06-15
  • 2017-05-13
  • 1970-01-01
  • 2021-07-16
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多