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
#2
I'm not observing the same thing as you
Output:
>>> d = {0:{'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1},1:{'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}} >>> 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 ... >>> populate(1, 'g', 2) >>> print d {0: {'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}, 1: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}}
I suspect I know what's going on though
Output:
>>> inner = {'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1} >>> d = {0: inner, 1: inner} >>> populate(1, 'g', 2) >>> d {0: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}, 1: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}}
In this second bit of code, I'm creating a single "inner" dictionary and re-using it. Note that in this case, the dictionary isn't copied, it's just reused. So when it gets mutated, that mutation is visible in two places. When you're constructing your outer dictionary, you probably want to copy the dictionary before inserting it.
Reply


Messages In This Thread
RE: Changing values in a dictionary within a dictionary - by micseydel - Apr-25-2018, 07:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using Lists as Dictionary Values bfallert 8 354 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  Matching Data - Help - Dictionary manuel174102 1 411 Feb-02-2024, 04:47 PM
Last Post: deanhystad
  Dictionary in a list bashage 2 572 Dec-27-2023, 04:04 PM
Last Post: deanhystad
  filtering a list of dictionary as per given criteria jss 5 701 Dec-23-2023, 08:47 AM
Last Post: Gribouillis
  need to compare 2 values in a nested dictionary jss 2 881 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  Sort a list of dictionaries by the only dictionary key Calab 1 504 Oct-27-2023, 03:03 PM
Last Post: buran
  python dictionary is that a bug ? rmangla 2 598 Sep-27-2023, 05:52 AM
Last Post: DPaul
  python dictionary syntax nafshar 2 885 Apr-24-2023, 07:26 PM
Last Post: snippsat
  Printing specific values out from a dictionary mcoliver88 6 1,431 Apr-12-2023, 08:10 PM
Last Post: deanhystad
  How to add list to dictionary? Kull_Khan 3 1,018 Apr-04-2023, 08:35 AM
Last Post: ClaytonMorrison

Forum Jump:

User Panel Messages

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