【发布时间】: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