PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How do I iterate over a dictionary for a specific key, then ading it to a new dictionary

 May 13, 2022     append, dictionary, python-3.x     No comments   

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": {

            }
        }
    }
}
  1. 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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing