【问题标题】:Merging different dictionaries together in one list将不同的字典合并到一个列表中
【发布时间】:2022-01-12 19:59:44
【问题描述】:

在这篇文章的指导下,我创建了 4 套不同的词典:Python variables as keys to dict。我现在想将所有这些字典合并到 1 个列表中。我尝试了以下方法:

classes = ['apple', 'orange', 'pear', 'mango']
class_dict = {}
store = []

for fruit in classes:
    if fruit == "orange":
        o = 2
        q = 1
    else:
        o = 0
        q = 0

    for j in ('fruit', 'o', 'q'):
        class_dict[j] = locals()[j]
    print (class_dict)
    store.append(class_dict)
print ("store: ", store)

输出如下图所示。如您所见,store 仅包含每次附加到它的同一字典的列表。我不确定我哪里出错了,我们将不胜感激!

{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}

store:  [{'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]

【问题讨论】:

  • 我无法理解您试图实现的目标。请为print(store)添加所需的输出
  • 已经添加了。请参阅我的问题的底部。
  • @peru_45 在我点击“发布您的答案”之前大约三秒钟,您删除了您的另一个问题。这是我写的:pastebin.com/ArJxA2X1
  • @Stef 谢谢你的回答;它帮助了我。如果您想在此处发布我的问题,我将取消删除它。

标签: python list dictionary local


【解决方案1】:

您需要将class_dict 移动到循环内。

classes = ['apple', 'orange', 'pear', 'mango']

store = []

for fruit in classes:
    class_dict = {}
    if fruit == "orange":
        o = 2
        q = 1
    else:
        o = 0
        q = 0

    for j in ('fruit', 'o', 'q'):
        class_dict[j] = locals()[j]
    print (class_dict)
    store.append(class_dict)
print ("store: ", store)

输出:

{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}
store:  [{'fruit': 'apple', 'o': 0, 'q': 0}, {'fruit': 'orange', 'o': 2, 'q': 1}, {'fruit': 'pear', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]

【讨论】:

    【解决方案2】:

    你应该在循环内移动class_dict

    classes = ['apple', 'orange', 'pear', 'mango']
    
    store = []
    
    for fruit in classes:
        class_dict = {}
        if fruit == "orange":
            o = 2
            q = 1
        else:
            o = 0
            q = 0
    
        for j in ('fruit', 'o', 'q'):
            class_dict[j] = locals()[j]
        print (class_dict)
        store.append(class_dict)
    print ("store: ", store)
    

    这是因为dict 在python 中是一个可变对象,并且在for 循环的每次迭代中,您都会更改全局变量class_dict 的值。简单的例子:

    >>> a = {'a': 1, 'b': 2}
    >>> a
    {'a': 1, 'b': 2}
    >>> b = a
    >>> b
    {'a': 1, 'b': 2}
    >>> b['c'] = 3
    >>> b
    {'a': 1, 'b': 2, 'c': 3}
    >>> a
    {'a': 1, 'b': 2, 'c': 3}
    

    当您在循环内移动class_dict 时,此变量变为局部变量,并且循环的迭代变得独立。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-19
      • 2017-01-05
      • 2017-04-11
      • 1970-01-01
      • 2017-11-27
      • 2021-04-10
      • 2019-03-12
      相关资源
      最近更新 更多