【问题标题】:Problems appending lists to dictionary in python在python中将列表附加到字典的问题
【发布时间】:2021-04-15 02:10:49
【问题描述】:

我正在使用此代码将值附加到 python 字典中:

df = {}

def set_key(dictionary, key, value):
     if key not in dictionary:
         dictionary[key] = value
     elif type(dictionary[key]) == list:
         dictionary[key].append(value)
     else:
         dictionary[key] = [dictionary[key], value]

list1 = ['a', 'b', 'c']
set_key(df, 'extra_contents', list1)
print(df)

output> {'extra_contents': ['a', 'b', 'c']}

问题是当我再次尝试执行此函数时,会发生以下情况:

list2 = ['d', 'e']
set_key(df, 'extra_contents', list2)
print(df)

output> {'extra_contents': ['a', 'b', 'c', ['d', 'e']]}

这是我想要的输出:

{'extra_contents': [['a', 'b', 'c'], ['d', 'e']]}

如何将当前输出转换为所需的输出?如果可能的话,只能通过更改我正在使用的功能。

我的主要目标是稍后将此 dict 转换为 pandas 数据框,因此,每个列表将是“extra_contents”列中的一行。

【问题讨论】:

  • 您想要的输出 {'extra_contents': ['a', 'b', 'c'], ['d', 'e']} 似乎不是一个有效的表达式。你是说{'extra_contents': [['a', 'b', 'c'], ['d', 'e']]} 还是{'extra_contents': ['a', 'b', 'c', 'd', 'e']}
  • 第一个! {'extra_contents': [['a', 'b', 'c'], ['d', 'e']]} 。刚刚编辑了问题以更正它!

标签: python list dictionary


【解决方案1】:

我想这就是你想要的:

def set_key(dictionary, key, value):
      if key in dictionary:
          dictionary[key].append(value)
      else:
          dictionary[key]=[value]

【讨论】:

  • 这很好,但如果我必须将值附加到不是列表的 dict 怎么办?假设我将在另一个键上附加以下内容:set_key(df, "new_key", 34) 该代码不会将 34 放入列表中吗?
  • 好的,但是还是有问题,每次插入一个新列表,都会在里面添加另一个列表。因此,如果我再次使用 list2 的函数,我的输出将是 {'extra_contents': [[['a', 'b', 'c'], ['d', 'e']], ['d', 'e']]} 而不是 {'extra_contents': [['a', 'b', 'c'], ['d', 'e'], ['d', 'e']]}
  • 实际上你以前的代码对我来说效果更好! def set_key(dictionary, key, value): if key in dictionary: dictionary[key].append(value) else: dictionary[key]=[value].
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 2020-12-06
  • 2023-02-02
  • 1970-01-01
  • 2013-03-27
  • 2019-03-29
  • 2019-11-07
相关资源
最近更新 更多