Jackson
Jackson

Reputation: 335

How to update a dictionary key that holds its values in a list?

I need to update a list based dictionary key without deleting the previous list items. However, from solutions, I find on google they are updating the value gets replaced completely. I want to still maintain the previous list items. I have a python dictionary that stores projects phases with the completed percentage. I wish to update the completed percentage until the whole phase is 100% complete. Here is my dictionary definition:

fiber_project = {"phase1":[10, 20,40,50], "phase2":[23, 39,90, 100],
                 "phase3":[30, 40,70, 100]}

This is how I am doing the update

#updating the phase2
fiber_project["phase2"] =[100]

Below is the output enter image description here

Upvotes: 0

Views: 47

Answers (2)

Amitai Irron
Amitai Irron

Reputation: 2055

This data structure is very useful, and python has a neat trick for constructing it, when you are adding an item to the value of some key, but do not already know if the key is in the dictionary or not. Naively, you would write (as I did initially):

if key not in d:
     d[key] = []
d[key].append(val)

This code uses 3 lines, and 2 to 3 accesses to the dictionary by key. You could limit the number accesses to a hard 2, at the cost of an extra code line, using:

if key in d:
    d[key].append(val)
else:
    d[key] = [val]

Or, you can have a single line and single dictionary access by key, using the dict.setdefault method:

d.setdefault(key, []).append(val)

Upvotes: 1

Samwise
Samwise

Reputation: 71434

Since fiber_project["phase2"] is a list, you can simply append to it:

fiber_project["phase2"].append(100)

Upvotes: 2

Related Questions