-1

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?

sudobangbang
  • 1,406
  • 10
  • 32
  • 55
  • while that does solve one problem, how do I know that band3Review is not already in there? additionally, how do I update the preexisting band1Review – sudobangbang Sep 15 '14 at 15:34
  • Where do `bandXreview` come from? Why not to make a dict `reviews={"band1":[...], "band3":[...] etc`? – georg Sep 15 '14 at 15:35
  • The answers to this question pretty much give you all the information and rationale to make your decision: http://stackoverflow.com/questions/38987/how-can-i-merge-union-two-python-dictionaries-in-a-single-expression – Aaron D Sep 15 '14 at 15:36
  • edited to make my question more clear – sudobangbang Sep 15 '14 at 15:36

2 Answers2

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

Result:

{'band1': ['good rhythm', 'cool performance', 'Not good', 'terrible'], 'band2': ['fast tempo', 'too loud'], 'band3Review': ['best band ever']}
Kevin
  • 74,910
  • 12
  • 133
  • 166
1

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]
Brett Lempereur
  • 815
  • 5
  • 11