Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating dictionary values
#1
I have a dictionary which looks like

 global_dict = {'GET': [1, 0, 0], 'POST': [1, 0, 0], 'PUT': [1, 0, 0], 'DELETE': [1, 0, 0]} 
I'm trying to increment the value of GET item only using

 global_dict[request.method][0]+=1 
But what's happening when I try that is this.

 global_dict = {'GET': [1, 0, 0], 'POST': [1, 0, 0], 'PUT': [1, 0, 0], 'DELETE': [1, 0, 0]} 
How do I update only list which is in GET alone and not the others.
Reply
#2
Your question is a bit confusing to me. You state that the problem is that all lists are updated but your example shows that none of the lists has changed. I think the original problem is that all lists are referencing the same object.

zeros = [0, 0, 0]
global_dict = {key: zeros for key in ['GET', 'POST', 'PUT', 'DELETE']}
global_dict['GET'][0] += 1
print(global_dict)
{'GET': [1, 0, 0], 'POST': [1, 0, 0], 'PUT': [1, 0, 0], 'DELETE': [1, 0, 0]}
Try this (create copies of the original list):
zeros = [0, 0, 0]
global_dict = {key: zeros.copy() for key in ['GET', 'POST', 'PUT', 'DELETE']}
global_dict['GET'][0] += 1
print(global_dict)
{'GET': [1, 0, 0], 'POST': [0, 0, 0], 'PUT': [0, 0, 0], 'DELETE': [0, 0, 0]}
Reply
#3
Smile Smile

Thanks man. That helped me a lot.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  need to compare 2 values in a nested dictionary jss 2 797 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  logging values from constantly updating CLI app imvirgo 1 503 Sep-27-2023, 05:01 PM
Last Post: deanhystad
  Printing specific values out from a dictionary mcoliver88 6 1,317 Apr-12-2023, 08:10 PM
Last Post: deanhystad
Question How to print each possible permutation in a dictionary that has arrays as values? noahverner1995 2 1,695 Dec-27-2021, 03:43 AM
Last Post: noahverner1995
  Getting values from a dictionary brunolelli 5 3,518 Mar-31-2021, 11:57 PM
Last Post: snippsat
  Python dictionary with values as list to CSV Sritej26 4 2,957 Mar-27-2021, 05:53 PM
Last Post: Sritej26
  Conceptualizing modulus. How to compare & communicate with values in a Dictionary Kaanyrvhok 7 3,905 Mar-15-2021, 05:43 PM
Last Post: Kaanyrvhok
  Values not updating for restful call boomramada 0 1,623 Mar-13-2021, 01:08 PM
Last Post: boomramada
  Adding keys and values to a dictionary giladal 3 2,429 Nov-19-2020, 04:58 PM
Last Post: deanhystad
  In this dictionary all the values end up the same. How? Pedroski55 2 1,896 Oct-29-2020, 12:32 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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