Python Forum

Full Version: Access to the elements of a dictionnary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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