Python Forum
Changing values in a dictionary within a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Changing values in a dictionary within a dictionary
#1
I am having a problem with over-accessing and changing values in a dictionary within a dictionary using the method 'startswith'.

I have a basic dictionary (the dictionary for which I want this to work is larger, hence the need for functions to do the work for me) for the trial:
 
d = {0:{'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1},1:{'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}} 
Now I want to change some values in only one of the interior dictionaries, so I define a function:
 
def populate(col, choice, start):
    for key in d[col]:
        if key.startswith(choice, start):#I use startswith because my real keys are longer
            d[col].update({key:0})    # or d[col][key]=0
and use
 
populate(1, 'g', 2)
This should change any value that ends in 'g' within the second inner dictionary, but not the first; yet it changes values that end in 'g' in the first inner dictionary, as can be seen:
d={0: {'lfm':1, 'lfg':0, 'lwg':0, 'lwm':1}, 1: {'lfm':1, 'lfg':0, 'lwg': 0, 'lwm': 1}}
I have done an intermediate print as the last line in the 'populate' function, within the 'if' statement, and it shows that it is picking up the right values but also changing the wrong values.

So why is d[col] not selecting only one dictionary.

Really frustrated.

John
Reply


Messages In This Thread
Changing values in a dictionary within a dictionary - by swannhouse - Apr-25-2018, 06:16 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Matching Data - Help - Dictionary manuel174102 1 354 Feb-02-2024, 04:47 PM
Last Post: deanhystad
  Dictionary in a list bashage 2 493 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 597 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  need to compare 2 values in a nested dictionary jss 2 797 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Sort a list of dictionaries by the only dictionary key Calab 1 452 Oct-27-2023, 03:03 PM
Last Post: buran
  python dictionary is that a bug ? rmangla 2 546 Sep-27-2023, 05:52 AM
Last Post: DPaul
  python dictionary syntax nafshar 2 840 Apr-24-2023, 07:26 PM
Last Post: snippsat
  Printing specific values out from a dictionary mcoliver88 6 1,317 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  How to add list to dictionary? Kull_Khan 3 951 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison
  Dictionary freethrownucleus 3 65,128 Mar-22-2023, 08:26 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020