Python Forum
Access to the elements of a dictionnary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Access to the elements of a dictionnary
#1
Hi,
i have the following json file contained in a file named file.conf
and i Need to replace the value of ENDPOINT witn something else


{"azure":{"ENDPOINT":"x","DB":"y","COL":"can"},"cache":{"path":"\path"},"queue":{"q":10},"log":{"log":"info"}}}
so i m trying to Access to this value first and set it to another value

here is my Code

with open('/home/file.conf', 'r') as file:
          json_data = json.load(file)
          print(type(json_data)) # it is a dictionnary 

          for item in json_data:
              for data_item in item['azure']:
                  data_item['ENDPOINT']="new value"


with open('/home/file.conf', 'w') as file:
          json.dump(json_data, file, indent=2) #try to replace the file value
but i m getting the following error

 for data_item in item['azure']:
TypeError: string indices must be integers
any help?
Reply
#2
When you do for item in json_data item represents the string "azure", because it goes through all the key values.
Try this -
json_data['azure']['ENDPOINT'] = 'new value'
and if you had multiple of these then
for item in json_data:
    json_data[item]['ENDPOINT'] = 'new value'
or maybe a list of certain ones to change
changelist = ['azure', 'comp', 'reft']

for item in json_data:
    if item in changelist:
        json_data[item]['ENDPOINT'] = 'newvalue'
You could also apply a dictionary to give different names different value
valueDict = {'azure' : 'x', 'comp' : 'a', 'reft' : 'p'}
changelist = ['azure', 'comp', 'reft']

for item in json_data:
    if item in changelist:
        json_data[item]['ENDPOINT'] = valueDict[item]
I hope this helps you
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,106 May-17-2022, 11:38 AM
Last Post: Larz60+
  Dictionnary indexing error Ander 6 1,859 Sep-10-2021, 12:22 PM
Last Post: Ander
  Sorting Elements via parameters pointing to those elements. rpalmer 3 2,581 Feb-10-2021, 04:53 PM
Last Post: rpalmer
  python dictionnary Omar_Yatim 3 2,807 Dec-08-2019, 05:12 AM
Last Post: scidam
  Dictionnary brackets issue Reldaing 1 1,818 Nov-10-2019, 11:54 PM
Last Post: ichabod801
  from Json Time Serie file to python dictionnary Reims 1 2,018 Sep-11-2019, 08:17 AM
Last Post: DeaD_EyE
  convert a json file to a python dictionnary of array Reims 2 2,233 Sep-10-2019, 01:08 PM
Last Post: Reims
  dictionnary lateublegende 1 2,441 Apr-29-2019, 09:10 PM
Last Post: Yoriz
  Why do we need setdefault() method for dictionnary? DJ_Qu 3 2,693 Apr-21-2019, 11:00 AM
Last Post: Gribouillis
  Json dictionnary on Redis katsu707 1 2,424 Dec-04-2018, 11:59 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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