'How to move a key in a dictionary to upper level in python? [closed]
I am trying to move 2 pairs of key-value "time:1000" and "time:5000" from below dictionary to upper level, and then delete the original one under "name". Below is the sample dict. I tried pop,
for d in dict["total"]:
d['time'] = d['name'].pop('time')
but code will return an error message, "type error, 'str' object cannot be interpreted as an integer". Appreciate any help. Thanks!
{
"total": [
{
"ID": "a1",
"name": [
{
"time": 1000,
"first_name": "Mary",
"last_name": "Jones"
},
{
"time": 1000,
"first_name": "John",
"last_name": "Brown"
}
]
},
{
"batch_id": "a2",
"name": [
{
"time": 5000,
"first_name": "Jason",
"last_name": "Williams"
},
{
"time": 5000,
"first_name": "Mickael",
"last_name": "Kol"
}
]
}
]
}
Below is the expected result,
{
"total": [
{
"ID": "a1",
"time": 1000,
"name": [
{
"first_name": "Mary",
"last_name": "Jones"
},
{
"first_name": "John",
"last_name": "Brown"
}
]
},
{
"batch_id": "a2",
"time": 5000,
"name": [
{
"first_name": "Jason",
"last_name": "Williams"
},
{
"first_name": "Mickael",
"last_name": "Kol"
}
]
}
]
}
Solution 1:[1]
Assuming d
the input dictionary, you can use:
for d1 in d['total']:
for d2 in d1['name']:
d1['time'] = d2.pop('time')
Note that this sets/overwrites the 'time' key as many times as there are dictionaries in the sublists (so if the values were different, the last one would prevail), but as we use pop
these apparently futile steps are also used to drop the entries. Also, the order is not exactly the same as the provided output.
output:
{'total': [{'ID': 'a1',
'name': [{'first_name': 'Mary', 'last_name': 'Jones'},
{'first_name': 'John', 'last_name': 'Brown'}],
'time': 1000},
{'batch_id': 'a2',
'name': [{'first_name': 'Jason', 'last_name': 'Williams'},
{'first_name': 'Mickael', 'last_name': 'Kol'}],
'time': 5000}]}
Solution 2:[2]
You can try this, it will go through the total list and fill in the index that you have running the time key based on the time key that is in the first index
a = {
"total": [
{
"ID": "a1",
"name": [
{
"time": 1000,
"first_name": "Mary",
"last_name": "Jones"
}
]
},
{
"batch_id": "a2",
"name": [
{
"time": 5000,
"first_name": "Jason",
"last_name": "Williams"
}
]
}
]
}
for (index, i) in enumerate(a['total']):
a['total'][index]['time'] = i['name'][0]['time']
del a['total'][index]['name'][0]['time']
print(a)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mozway |
Solution 2 | Miguel Vieira Colombo |