Issue
I know this is a noob question but I'm a new learner to Python and I'm struggling with dictionaries.
I think my code is right but I'm not sure.
What I am trying to achieve is that I want to iterate over a dictionary with a list items with a dictionary in it. If the value is == None then that key Should be skipped. but if there is a value. I want to append the Key:Value pair to the pmp_dict = {}
Here is my code:
input_dict = {
"operation": {
"Details": {
"ACCOUNTLIST": {
"RESOURCENAME": "abbas",
"ACCOUNTNAME": "account_name",
"RESOURCETYPE":None,
"PASSWORD": "password"
}
}
}
}
pmp_dict= {
"operation": {
"Details": {
"ACCOUNTLIST": [
{
}
]
}
}
}
print(pmp_dict)
for list_item in input_dict["operation"]["Details"]["ACCOUNTLIST"]:
for key, value in list_item.items():
if value == None:
pass
else:
pmp_dict["operation"]["Details"]["ACCOUNTLIST"][key]=value
what Im struggling with is the last 5 lines. how do i write so that i achieve the desired outcome? i know what i want to do but not the syntax for it.
Solution
There's 2 problems with the code you have:
1.pmp_dict["operation"]["Details"]["ACCOUNTLIST"]
isn't a dictionary, it's a list. Unless this was intentional, I would replace
pmp_dict= {
"operation": {
"Details": {
"ACCOUNTLIST": [
{
}
]
}
}
}
with
pmp_dict = {
"operation": {
"Details": {
"ACCOUNTLIST": {
}
}
}
}
- You don't need to iterate through the dictionary using
for list_item in input_dict["operation"]["Details"]["ACCOUNTLIST"]:
So instead, replace the last 6 lines of your code with
for key, value in input_dict["operation"]["Details"]["ACCOUNTLIST"].items():
if value == None:
pass
else:
pmp_dict["operation"]["Details"]["ACCOUNTLIST"][key] = value
Answered By - Hartsaxena Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.