如何在python中更新字典值?

时间:2014-09-15 15:32:50

标签: python dictionary

让我们说我的字典如下所示:

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"]}

我也想有效地做到这一点,没有繁琐的循环可能会减慢我的程序。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

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']}

答案 1 :(得分:1)

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

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

一切都很好。你说你要避免"乏味"循环;我不太确定这意味着什么,但您肯定可以使用extend类型上的list方法来避免循环:

>>> newb = [6, 7, 8]
>>> container["b"].extend(newb)
>>> container["b"]
[4, 5, 6, 7, 8]