- I want delete a single element inside a key
documents
, the list size can vary, so first I am counting the number of items inside list, and then I want to delete theObject
element fromdocuments
list. - I want to basically run the python for loop depending upon the list size, and delete the element from it. Not able to really figure out an approach for for loop.
- Input
{
"UserCode": "<user>",
"ObjectType": "Document",
"documents": [
{
"Object": "<base-64-string1>",
"ObjectSourceFileName": "A1.json",
"ContextKey": "A1.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"Object": "<base-64-string2>",
"ObjectSourceFileName": "A2.json",
"ContextKey": "A2.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"Object": "<base-64-string3>",
"ObjectSourceFileName": "A3.json",
"ContextKey": "A3.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"Object": "<base-64-string4>",
"ObjectSourceFileName": "A4.json",
"ContextKey": "A4.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
}
],
"ClientCode": "CL",
"Source": "Client"
}
- Expected Output
{
"UserCode": "<user>",
"ObjectType": "Document",
"documents": [
{
"ObjectSourceFileName": "A1.json",
"ContextKey": "A1.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"ObjectSourceFileName": "A2.json",
"ContextKey": "A2.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"ObjectSourceFileName": "A3.json",
"ContextKey": "A3.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
},
{
"ObjectSourceFileName": "A4.json",
"ContextKey": "A4.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv"
}
],
"ClientCode": "CL",
"Source": "Client"
}
CodePudding user response:
You can use del
to remove the key from dictionary:
dct = ... your dictionary from the question ...
for doc in dct["documents"]:
del doc["Object"]
print(dct)
Prints:
{
"UserCode": "<user>",
"ObjectType": "Document",
"documents": [
{
"ObjectSourceFileName": "A1.json",
"ContextKey": "A1.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv",
},
{
"ObjectSourceFileName": "A2.json",
"ContextKey": "A2.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv",
},
{
"ObjectSourceFileName": "A3.json",
"ContextKey": "A3.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv",
},
{
"ObjectSourceFileName": "A4.json",
"ContextKey": "A4.json2022-08-010T09:40:06.429358",
"ObjectFormat": "csv",
},
],
"ClientCode": "CL",
"Source": "Client",
}