npatel
npatel

Reputation: 1111

getting desired value from dictionary based on another value

I have following output from a dictionary.

{'001': {'desc': 'Verify all commands.', 'result': 'P', 'name': '001', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'}, 
'002': {'desc': 'Verify all commands.', 'result': 'F', 'name': '002', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'}}

What I want is get name from it where result is F? It will be helpful if someone can show me the way to achieve desired output.

Upvotes: 0

Views: 62

Answers (2)

thefourtheye
thefourtheye

Reputation: 239583

This will the list of all the names where result is F

data = {'001': {'desc': 'Verify all commands.', 'result': 'P', 'name': '001', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'}, 
'002': {'desc': 'Verify all commands.', 'result': 'F', 'name': '002', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'},
'003': {'desc': 'Verify all commands.', 'result': 'F', 'name': '003', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'}}

print [value["name"] for key, value in data.items() if value["result"] == "F"]

Output

['002', '003']

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

Iterate over dict.values:

for v in my_dict.values():
   if v['result'] == 'F':
      print v['name']

Demo:

my_dict = {'001': {'desc': 'Verify all commands.', 'result': 'P', 'name': '001','run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'},
           '002': {'desc': 'Verify all commands.', 'result': 'F', 'name': '002', 'run_time': '00:00:30', 'start_time': '1382943624', 'end_time': '1382943654'}          }
for v in my_dict.values():
   if v['result'] == 'F':
      print v['name']

output:

002

Upvotes: 2

Related Questions