Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get key filtered by its value in multidimensional array Python

I got this data

employee_detail_list = {
      'John Doe': {
          'name': 'EMP-0001',
          'first_name': 'John',
          'last_name': 'Doe',
          'full_name': 'John Doe',
          'company': 'Company 1'
      },
      'Tom Smith': {
          'name': 'EMP-0002',
          'first_name': 'Tom',
          'last_name': 'Smith',
          'full_name': 'Tom Smith',
          'company': 'Company 2'
      },
      'Andrew Sebastian': {
          'name': 'EMP-0003',
          'first_name': 'Andrew',
          'last_name': 'Sebastian',
          'full_name': 'Andrew Sebastian',
          'company': 'Company 2'
      },   }

i want output

Tom Smith
Andrew Sebastian

by filtering value "Company 2", i’ve try this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# list out keys and values separately
key_list = list(employee_detail_list.keys())
val_list = list(employee_detail_list.values())

# print key with val Company 2
position = val_list.index("Company 2")
print(key_list[position])

but always ended up with this error:

ValueError: 'Company 2' is not in list

any thought what is wrong? thanks before

>Solution :

It does what you need. .items() returns data as iterable objects that can be traversed.

for key, value in employee_detail_list.items():
    if value["company"] == "Company 2":
        print(key)

# Output
Tom Smith
Andrew Sebastian

The problem with your solution is that val_list = list(employee_detail_list.values()) returns a list with objects and you are trying to find val_list.index("Company 2") by string which is not there

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading