Reputation: 13
I have a list of dictionaries, and I want to cycle through them and replace one of the values. The value I'm replacing is a dictionary, and I want to replace it with one of the values from the same dictionary.
Below is one of the dictionaries in the list.
{'id': '123abc',
'name': 'Metrics',
'rows': 0,
'columns': 0,
'owner': {'id': 123, 'name': 'John Doe'},
'dataCurrentAt': '2017-03-24T14:32:33Z',
'createdAt': '2017-03-24T14:32:33Z',
'pdpEnabled': False}
So I'm trying to replace the entire 'owner' value with just 'name' from the 'owner' dictionary. I hope that makes sense. Below is the section of the Python script where I have attempted to do this.
for dictionary in dataset_list:
for key, value in dictionary.items():
if key == "owner":
owner = value.get("name")
value = owner
Upvotes: 1
Views: 754
Reputation: 2272
for dictionary in dataset_list:
for key, value in dictionary.items():
if key == "owner":
dictionary["owner"] = dictionary["owner"]["name"]
Upvotes: 1
Reputation: 7268
You can try:
>>> dataset_list = {'id': '123abc', 'name': 'Metrics', 'rows': 0, 'columns': 0, 'owner': {'id': 123, 'name': 'John Doe'}, 'dataCurrentAt': '2017-03-24T14:32:33Z', 'createdAt': '2017-03-24T14:32:33Z', 'pdpEnabled': False}
>>> for k,v in dataset_list.iteritems():
if k == "owner":
owner = v["name"]
dataset_list[k] = owner
>>> dataset_list
{'rows': 0, 'createdAt': '2017-03-24T14:32:33Z', 'name': 'Metrics', 'pdpEnabled': False, 'owner': 'John Doe', 'id': '123abc', 'columns': 0, 'dataCurrentAt': '2017-03-24T14:32:33Z'}
Upvotes: 1
Reputation: 95948
If I understand you correctly, all what you need to do is:
dictionary["owner"] = dictionary["owner"]["name"]
This will change the value of the key "owner", to the value of the key "name".
Upvotes: 2
Reputation: 82765
A = {'id': '123abc', 'name': 'Metrics', 'rows': 0, 'columns': 0, 'owner': {'id': 123, 'name': 'John Doe'}, 'dataCurrentAt': '2017-03-24T14:32:33Z', 'createdAt': '2017-03-24T14:32:33Z', 'pdpEnabled': False}
A["owner"] = A["owner"]["name"]
print A
Output:
{'rows': 0, 'createdAt': '2017-03-24T14:32:33Z', 'name': 'Metrics', 'pdpEnabled': False, 'owner': 'John Doe', 'id': '123abc', 'columns': 0, 'dataCurrentAt': '2017-03-24T14:32:33Z'}
Upvotes: 1