0

For example I have this nested dictionary:

D = {'emp1': {'name': 'Bob', 'job': 'Mgr'},
     'emp2': {'name': 'Kim', 'job': 'Dev'},
     'emp3': {'name': 'Sam', 'job': 'Dev'}}

How do I print all the information when the user inputs their name (ex: 'Bob')? For example, the user is asked to enter an employee name to search for all the information about that name:

Employee ID: emp1
Employee Name: Bob
Job: Mgr
t l n
  • 25
  • 4
  • Does this answer your question? [Access an arbitrary element in a dictionary in Python](https://stackoverflow.com/questions/3097866/access-an-arbitrary-element-in-a-dictionary-in-python) – Nathaniel D. Hoffman May 17 '20 at 21:09

3 Answers3

2

loop over your dictionary using items:

for key, value in D.items():
    if "Bob" in value['name']:
        print(f"Employee ID: {key}")
        print(f"Employee Name:: {value['name']}")
        print(f"Employee ID: {value['job']}")
Hozayfa El Rifai
  • 1,432
  • 7
  • 17
1

Something like this will do:

name = input('Enter employee name: ')
for k, v in D.items():
    if v['name'] == name:
        print('Employee ID:', k)
        print('Employee Name:', v['name'])
        print('Job:', v['job'])

input('your prompt message') will prompt the user for user input and return the entered value.

xcmkz
  • 677
  • 4
  • 15
0

The most efficient solution here is to reform your data structure so that name was the key to all other info:

new_d = {values['name']: {'job': values['job'], 'id': key} for key, values in D.items()}

Now you can access all info just by one operation with O(1):

name = input("Enter name")
info = new_d[name]
print("Employee ID:", info['id'])
print("Employee Name:", name)
print("Job:", info['job'])
Michail Highkhan
  • 517
  • 6
  • 18