如何在python中更新字典值?

2024-05-29 07:13:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一本如下所示的词典:

dict1 = {band1Review: ["good rhythm", "cool performance"], band2Review: ["fast tempo", "too loud"]}
band1Review = ["Not good", "terrible"]
band3Review = ["best band ever"]

如果我知道我有这两个新的评论,有没有一种方法可以让我现有的字典看起来像下面这样?你知道吗

dict1 = {band1Review: ["good rhythm", "cool performance", "Not good", "terrible"], band2Review: ["fast tempo", "too loud"], band3Review: ["best band ever"]}

我也希望这样做有效率,没有乏味的循环,可能会减慢我的程序。有什么建议吗?你知道吗


Tags: performancenottoofastbestgoodcoolloud
2条回答

字典中存储的列表是可变的,可以就地更新。例如,可以使用append附加单个项:

>>> container = {"a": [1, 2], "b": [4, 5]}
>>> container["a"]
[1, 2]
>>> container["a"].append(3)
>>> container["a"]
[1, 2, 3]

一切都很好。您声明希望避免“冗长”的循环;我不太清楚这意味着什么,但您当然可以使用list类型上的extend方法避免循环:

>>> newb = [6, 7, 8]
>>> container["b"].extend(newb)
>>> container["b"]
[4, 5, 6, 7, 8]
dict1 = {"band1": ["good rhythm", "cool performance"], "band2": ["fast tempo", "too loud"]}
band1Review = ["Not good", "terrible"]
band3Review = ["best band ever"]

dict1.setdefault("band1", []).extend(band1Review)
dict1.setdefault("band3Review", []).extend(band3Review)
print dict1

结果:

{'band1': ['good rhythm', 'cool performance', 'Not good', 'terrible'], 'band2': ['fast tempo', 'too loud'], 'band3Review': ['best band ever']}

相关问题 更多 >

    热门问题