Reputation: 5
So I'm new to phython, and I was wondering on how I could modify(adding or subtracting) each individual "x" in one go.
"Position": {
"7,-5": {
"id": "58",
"y": -5,
"x": 7
},
"2,-4": {
"id": "183",
"y": -4,
"x": 2
},
"-4,-1": {
"id": "190",
"y": -1,
"x": -4
}
I tried doing
import json
with open ('position.txt', 'r+') as f:
position_data = json.load(f)
position_data['Position']['x'] = +1
TypeError: list indices must be integers or slices, not str
This is what I want
"Position": {
"7,-5": {
"id": "58",
"y": -5,
"x": 8
},
"2,-4": {
"id": "183",
"y": -4,
"x": 3
},
"-4,-1": {
"id": "190",
"y": -1,
"x": -3
}
I'm not sure on how to go from here. Please advice.
Upvotes: 0
Views: 68
Reputation: 2520
you could do something like this:
for key in position_data['Position'].keys():
position_data['Position'][key]['x'] += 1
Upvotes: 3
Reputation: 36033
for value in position_data['Position'].values():
value['x'] += 1
Use itervalues
in Python 2 for better efficiency.
Demo (since I got downvoted without explanation):
from pprint import pprint
position_data = {
"Position": {
"7,-5": {
"id": "58",
"y": -5,
"x": 7
},
"2,-4": {
"id": "183",
"y": -4,
"x": 2
},
"-4,-1": {
"id": "190",
"y": -1,
"x": -4
}
}
}
pprint(position_data)
for value in position_data['Position'].values():
value['x'] += 1
pprint(position_data)
Output:
{'Position': {'-4,-1': {'id': '190', 'x': -4, 'y': -1},
'2,-4': {'id': '183', 'x': 2, 'y': -4},
'7,-5': {'id': '58', 'x': 7, 'y': -5}}}
{'Position': {'-4,-1': {'id': '190', 'x': -3, 'y': -1},
'2,-4': {'id': '183', 'x': 3, 'y': -4},
'7,-5': {'id': '58', 'x': 8, 'y': -5}}}
Upvotes: 3