Reputation: 57
I have this main_dict
created and want to see if main_dict[x]["Description"]
exists or not, and if yes, then delete it. Where x
is 'pins'
, 'nails'
, 'board'
, etc ...
main_dict = {
'pins':
{
'Category': ['General'],
'Contact': ['Mark'],
'Description': ['This', 'is', 'a']
},
'nails':
{
'Category': ['specific'],
'Contact': ['Jon'],
'Description': ['This', 'is', 'a', 'description']
},
'board':
{
'Category': ['General'],
'Contact': ['Mark'],
'Description': ['This', 'is', 'a']
},
'hammer':
{
'Category': ['tools'],
'Contact': ['Jon'],
'Description': ['This', 'is', 'a', 'description']
}
}
I tried this:
for x in main_dict:
del main_dict[x]["Description"]
This returns error if main_dict[x]["Description"]
does not exist.
Also this does not work:
if main_dict[x]["Description"] in mainDict[x]:
del main_dict[x]["Description"]
Upvotes: 0
Views: 75
Reputation: 123473
This would remove it from any sub-dictionaries that contain it:
main_dict = {
'pins':
{
'Category': ['General'],
'Contact': ['Mark'],
'Description': ['This', 'is', 'a']
},
'nails':
{
'Category': ['specific'],
'Contact': ['Jon'],
'Description': ['This', 'is', 'a', 'description']
},
'board':
{
'Category': ['General'],
'Contact': ['Mark'],
'Description': ['This', 'is', 'a']
},
'hammer':
{
'Category': ['tools'],
'Contact': ['Jon'],
'Description': ['This', 'is', 'a', 'description']
}
}
for key, value in main_dict.items():
if isinstance(value, dict) and 'Description' in value:
del value['Description']
Result:
{
'pins':
{
'Category': ['General'],
'Contact': ['Mark'],
},
'nails':
{
'Category': ['specific'],
'Contact': ['Jon'],
},
'board':
{
'Category': ['General'],
'Contact': ['Mark'],
},
'hammer':
{
'Category': ['tools'],
'Contact': ['Jon'],
}
}
Upvotes: 0
Reputation: 1866
To check if a key is in a dictionary try if key in dict
to check in nested dictionaries you follow the same logic:
for key in main_dict:
if 'Description' in main_dict[key]:
# do something
About removing an element, you should indeed use the del
statement. I copied your main_dict, and ran the same as you:
for x in main_dict:
del main_dict[x]['Description']
Maybe you're trying to remove it twice?
Upvotes: 0
Reputation: 23504
You simply use pop()
method with default argument(e.g. None
) to omit checking if "Description"
exist as key.
for i in main_dict:
main_dict[i].pop("Description", None)
Note: it's not a good practice to change iterable object while iterating over it.
Upvotes: 4
Reputation: 3968
Here's a simple solution:
for x in main_dict:
if "Description" in main_dict[x]:
main_dict[x].pop("Description")
Upvotes: 2