How do I access using Python Dict and List

Question:

Here I am giving two variables namely "a", "result". If "result" matches with any of the record in "a" in "city" then it should return entire record of the "a" variable.

a = {
    "output": [
        {"name": "India",
        "state": [
            {
                "city": ["c", "d" ]
            }
        ],
        "city": [
            "g",
            "h"
        ]},
        {"name": "Telangana",
        "state": [
            {
                "city": ["a", "b" ]
            }
        ],
        "city": [
            "e",
            "f"
        ]}
        ]
    }
result = "e"

Expected results :

1)result="e"
then it should return final output=

{"name": "Telangana",
            "state": [
                {
                    "city": ["a", "b" ]
                }
            ],
            "city": [
                "e",
                "f"
            ]}

for ex2:
2)result="d"
final output is

  {"name": "India",
            "state": [
                {
                    "city": ["c", "d" ]
                }
            ],
            "city": [
                "g",
                "h"
            ]}

Tried Code :

def filter(data,result):
    for item in a["output"]:
        for value in item.get('city',[]):
            if value==result:
                print(item)
            else:
                item.get('state',[])
                print(filter(item['state'],result))
filter(a,result)
Asked By: Perl_Newbie

||

Answers:

You haven’t mentioned values not existing, so the easiest approach would be to do this:

def filter_city(result):
    for item in a["output"]:
        if result in [*item["state"][0]["city"], *item["city"]]:
            return item
    return None

print(filter_city("e"))
print(filter_city("d"))

Output:

{'name': 'Telangana', 'state': [{'city': ['a', 'b']}], 'city': ['e', 'f']}
{'name': 'India', 'state': [{'city': ['c', 'd']}], 'city': ['g', 'h']}
Answered By: B Remmelzwaal

First inside your function filter you’re using the a variable instead of the parameter data.

Second you’re checking if the current value is equal to the result, that’s okey but what you do in the else statement you should move it outside the inner for loop and use a flag to check if you found the match or not.

    def filter(data,result):
      for item in data["output"]:
        founded = False
        for value in item.get('city',[]):
          if value==result:
            print(item)
        if not founded:
          item.get('state',[])
          print(filter(item['state'], result))

I didn’t test it but it should work! Feel free to test it and refactor it.

Answered By: Jordi Bustos
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.