gpt4 book ai didi

python - 将列表附加到字典以获取嵌套列表

转载 作者:行者123 更新时间:2023-11-28 22:19:43 28 4
gpt4 key购买 nike

我一直在尝试弄清楚如何将列表添加到字典中,并因此在字典值中获取嵌套列表。这是一个虚拟代码作为示例:

IN:

pets = dict()
pets['cat'] = list(['stray','brown','big'])
new_val = list(['house','white','small'])
pets['cat'].append(new_val)
print(pets)

OUT:
{'cat': ['stray', 'brown', 'big', ['house', 'white', 'small']]}

我正在尝试获取两个列表的列表:

{'cat': [['stray', 'brown', 'big'], ['house', 'white', 'small']]}

最佳答案

在我看来,最简洁的方法是将值实例化为一个空列表。然后按顺序附加列表。

pets = {}
pets['cat'] = []

old_val = ['stray','brown','big']
pets['cat'].append(old_val)

new_val = ['house','white','small']
pets['cat'].append(new_val)

如果您经常这样做,请使用 collections.defaultdict 这样您就不必手动实例化键和空列表:

from collection import defaultdict

pets = defaultdict(list)

old_val = ['stray','brown','big']
pets['cat'].append(old_val)

new_val = ['house','white','small']
pets['cat'].append(new_val)

结果:

{'cat': [['stray', 'brown', 'big'],
['house', 'white', 'small']]}

关于python - 将列表附加到字典以获取嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49519560/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com