【问题标题】:How to create a dictionary with nested dictionary with multiple key value pairs using a loop?如何使用循环创建具有多个键值对的嵌套字典的字典?
【发布时间】:2021-12-04 12:53:54
【问题描述】:

您好,我正在构建一个网络抓取程序,并且正在努力以某种我想要的方式创建字典,但经过数小时的搜索,我没有发现任何与我正在尝试做的事情过于相似的东西。

这些是我想合并成字典的列表。

number = [1,2]
attributes = [' 75 cm', ' 3 cm', ' 125 cm', ' 7.30 kg', ' 1', ' 27 cm', ' 9 cm', ' 71 cm', ' 21.70 kg', ' 1']
measure_without_duplicates = ['Width:', 'Height:', 'Length:', 'Weight:', 'Package(s):']

这是我想要创建字典的具体方式:

dictionary = {1 : {'Width:':' 75 cm', 'Height:':' 3 cm', 'Length:':' 125 cm', 'Weight:': '7.30 kg', 'Package(s):':' 1'}, 2: {'Width:':' 27 cm', 'Height:':' 9 cm', 'Length:':' 71 cm', 'Weight:': '21.70 kg', 'Package(s):':' 1'}

它将需要重复 measure_without_duplicates 中的项目作为属性值的键所需的次数,具体取决于有多少数字。

本例中有2个,所以需要迭代两次,因为一个产品需要两个包。这些度量需要与属性数组相关联,但这些不会重复,而是延续到下一个包。

我无法将列表与属性拼接,因为列表至少可以包含 5 个项目,具体取决于需要多少包。就像我说的,这是一个网页抓取项目,所以我需要能够拥有灵活的代码。

我创建了一个名为 measure_without_duplicates 的变量的原因是因为我的程序中有另一个名为 measure 的数组,看起来像这样:

measure = ['Width:', 'Height:', 'Length:', 'Weight:', 'Package(s):', 'Width:', 'Height:', 'Length:', 'Weight:', 'Package(s):']

我写了一个小代码,从列表中删除任何重复。

我尝试为这个问题编写一些代码,但是如果没有发生错误,它就无法工作。我已经尝试过其他的东西,但我很难获得以前的尝试,所以我只写下我拥有的最新代码:

for key in range(len(number)):
    for iteration in range(len(measure_without_duplicates)):
        dictionary[str(key+1)][measure_without_duplicates[iteration]]=attributes[iteration]
print(dictionary)

我得到一个错误:

    dictionary[str(key+1)][measure_without_duplicates[iteration]]=attributes[iteration]
KeyError: '1'

非常感谢您的帮助,感谢您的宝贵时间。

【问题讨论】:

    标签: python arrays dictionary


    【解决方案1】:

    使用iterzipiter 将确保你只迭代它你消耗了多少,在这里它允许我们在我们离开的地方重新开始迭代:

    number = [1,2]
    attributes = [' 75 cm', ' 3 cm', ' 125 cm', ' 7.30 kg', ' 1', ' 27 cm', ' 9 cm', ' 71 cm', ' 21.70 kg', ' 1']
    measure_without_duplicates = ['Width:', 'Height:', 'Length:', 'Weight:', 'Package(s):']
    
    attrs = iter(attributes)
    
    print({i: dict(zip(measure_without_duplicates, attrs)) for i in number})
    

    {1: {'Width:': ' 75 cm', 'Height:': ' 3 cm', 'Length:': ' 125 cm', 'Weight:': ' 7.30 kg', 'Package(s):': ' 1'}, 2: {'Width:': ' 27 cm', 'Height:': ' 9 cm', 'Length:': ' 71 cm', 'Weight:': ' 21.70 kg', 'Package(s):': ' 1'}}
    

    【讨论】:

    • 谢谢,这正是我所需要的!
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2019-09-30
    • 2021-07-25
    • 2019-03-29
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多