0

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:

# 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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@FahmiSabilaDinnulhaq if I answered your question, don't forget to mark it as correct)
1

You can use filter()

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'
      }
}

def isFromCompany2(data):
    return data["company"] == "Company 2"

result = filter(isFromCompany2, employee_detail_list.values())

print(list(result))

This is a nice article that explains it https://realpython.com/python-filter-function/

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.