-2

I am defining a list of dictionaries and I need to print only the one dictionary based on my input in check_if_in_list

first_list = {'a':'1','b':'2'}
second_list = {'a':'10','b':'20'}

all_lists =[first_list, second_list]

for element in all_lists:
  check_if_in_list = input('give a valid number')
  if check_if_in_list = (item['a'] for item in all_lists):

I need something like that

print(element where item['a]=check_if_in_list)

for example if I enter '1' in input in check_if_in_list, the print should be :

{'a':'1','b':'2'}
Antouil
  • 63
  • 10

1 Answers1

2

This will give you the output you require. If I have interpreted your requirement correctly, it's actually much simpler than the (I assume) semi-pseudocode that you posted.

first_dict = {'a':'1','b':'2'}
second_dict = {'a':'10','b':'20'}

all_dicts =[first_dict, second_dict]

check_if_in_list = input('give a valid number')
for element in all_lists:
    if check_if_in_list == element['a']:
        print(element) 

If you need it as a comprehension, this would work:

print(*[element for element in all_lists if element['a'] == check_if_in_list])

This utilises star-unpacking to return the values of the list for printing, which should either be a dictionary or nothing in your case. (Thanks to @HampusLarsson for the reminder).

If your original code, you're looping over all_lists twice, which is unnecessary.

David Buck
  • 3,752
  • 35
  • 31
  • 35