简体   繁体   中英

How to update a dictionary value in python?

Lets say I have a dictionary that looks like the following:

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

If I know that I have these 2 new reviews, is there a way I can manipulate my pre-existing dictionary to look like the following?

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

I also want to do this efficiently, without tedious loops that may slow my program. Any suggestions?

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

Result:

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

The list stored within the dictionary is mutable, and can be updated in-place. As an example, you can append single items with append :

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

All well and good. You state that you want to avoid "tedious" loops; I'm not quite sure what this means, but you certainly can avoid looping in your case with the extend method on the list type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM