【问题标题】:Python Multiple Dictonary Values into one ListPython 将多个字典值合并到一个列表中
【发布时间】:2022-11-14 19:49:54
【问题描述】:

所以我使用xml.etree.ElementTree 读取文件夹中的多个.xml。

我使用x.attrib 提取所需的属性并将它们放入变量中。

attributes = x.attrib

存储的信息来自多个字典:

{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_1'}
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_2'}
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_3'}
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_4'}
{'Key1': 'Value1', 'Key2': 'Value2', 'Key3': 'Value3', 'Key4': 'Value4', 'Key5': 'Value_5'}

现在我尝试遍历所有这些并将所有 Key5 值放入一个列表中:

list = []
for dict in attributes:
            list.append(attributes.get("Key5"))

当前输出为:

['Value_5', 'Value_5', 'Value_5', 'Value_5', 'Value_5']

【问题讨论】:

  • 问题是什么?
  • 你的意思是dict.get("Key5") 因为 dict 是循环变量。?
  • 不是除非你是受虐狂,否则使用内置类型作为变量名(例如,dict、list)

标签: python


【解决方案1】:

我认为您正在尝试这样做:

attributes = x.attrib

l = []
for d in attributes: # <-- we iterate over attributes here, and put each value in "attributes" list into "d"
    l.append(d.get("Key5")) # <-- note we are referring to "d" here
print(l)

注意:使用“list”和“dict”作为变量名不是一个好主意,因为它们是 Python 中的保留名称,所以我重命名了它们,但也许“result”和“item”更好

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2013-03-19
    • 2019-03-12
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多