1

I have this sample json data in a list:

data = [ 
  { "Name": "John_Doe", "Age" : 25 } 
  { "Name": "Jane_Roe", "Age" : 26 }
]

I need a way to extract the all the key value pairs from an element in the list based on the 'Name' Key. If my variable = 'John_Doe', then the script should only return the values related to John_Doe, i, e only the following values :

{ "Name": "John_Doe", "Age" : 25 }
1
  • 2
    [x for x in data if x["Name"]=="John_Doe"]? Commented Dec 14, 2017 at 5:31

3 Answers 3

1

Just extract all the dictionaries with the value "John_Doe" associated with the key "Name":

print([d for d in data if d['Name'] == "John_Doe"])
# [{ "Name": "John_Doe", "Age" : 25 }]

Or with filter():

print(list(filter(lambda x : x['Name'] == "John_Doe", data)))
# [{ "Name": "John_Doe", "Age" : 25 }]
Sign up to request clarification or add additional context in comments.

Comments

1

If all you need is the dict with a Name element matching John_Doe, then:

matches = [m for m in data if "Name" in m and m["Name"] == "John_Doe"]

You can unroll this list comprehension to see what it does:

matches = []
for m in data:
    if "Name" in m and m["Name"] == "John_Doe":
        matches.append[m]

Comments

1
def get_details(data, name):
    for i in data:
        if i['Name'] == name:
            return i
    return {}

data = [{"Name": "John_Doe", "Age" : 25 },{"Name": "Jane_Roe", "Age" : 26 }]
name = "John_Doe"
get_details(data, name)

output:

{'Age': 25, 'Name': 'John_Doe'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.