Home > other >  Python Accessing a Value in a List of Dictionaries, if another Value in the Dictionary Exists
Python Accessing a Value in a List of Dictionaries, if another Value in the Dictionary Exists

Time:01-08

My question is an extension to this:

Python Accessing Values in A List of Dictionaries

I want to only return values from dictionaries if another given value exists in that dictionary.

In the case of the example given in the linked question, say I only want to return 'Name' values if the 'Age' value in the dictionary is '17'.

This should output

'Suzy' 

only.

CodePudding user response:

result = [d["Name"] for d in dicts if d.get("Age") == 17)]

Of course this would select all nanes that satisfy the condition. You can put that in a function.

CodePudding user response:

In the following case :

list= [  
    {'Name': 'Albert' , 'Age': 16},
    {'Name': 'Suzy', 'Age': 17},
    {'Name': 'Johnny', 'Age': 13}
]

If you want return only people Name when "age == 17" use :

for d in list:
    if  d['Age'] == 17 :
        print (d['Name'])

Use a condition inside your for.

  •  Tags:  
  • Related